Node.js The use of Express framework

Keywords: Web Server npm Database Javascript

Node.js The use of Express framework

Node.js The use of Express framework

1 Introduction to express framework

1.1 introduction and features of express framework

1. Introduction to express:
Express is a web application development framework based on Node platform, which provides a series of powerful features to help you create various web applications.
We can use the npm install express command to download.

2.Express framework features:

  • It provides a convenient and concise way to define routes
  • Simplified processing of getting HTTP request parameters
  • High support for template engine, easy to render dynamic HTML pages
  • Middleware mechanism is provided to effectively control HTTP requests
  • Have a large number of third-party middleware to expand functions

1.2 preliminary use of Express

Using express framework to create web server is very simple, just call the function returned by express module.

// Introducing the express framework
const express = require('express');
// Create web server
const app = express();

app.get('/' , (req, res) => {
	// send()
	// 1. The type of response content will be detected inside the send method
	// 2. The send method will automatically set the http status code
	// 3. The send method will help us set the content type and code of the response automatically
	res.send('Hello. Express');
})

app.get('/list', (req, res) => {
	res.send({name: 'Zhang San', age: 20})
})

// Listening port
app.listen(3000);
console.log('Website server started successfully');

2 Express framework Middleware

2.1 middleware introduction

1. Middleware is a bunch of methods, which can receive the request from the client, respond to the request, or continue to deliver the request to the next middleware for further processing.

2. Middleware consists of two parts: middleware method and request processing function.
The middleware method is provided by Express, which is responsible for intercepting the request. The request processing function is provided by the developer, which is responsible for processing the request.

 app.get('Request path', 'Processing function')   // Receive and process get requests
 app.post('Request path', 'Processing function')  // Receive and process post requests

3. Multiple middleware can be set for the same request to process the same request multiple times.
By default, requests match middleware from top to bottom. Once the match is successful, the match is terminated.
You can call the next method to give control of the request to the next middleware until you encounter the middleware that ended the request.

 app.get('/request', (req, res, next) => {
     req.name = "Zhang San";
     next();
 });
 app.get('/request', (req, res) => {
     res.send(req.name);
 });

two point two app.use Usage of Middleware

app.use Match all the request methods. You can directly pass in the request processing function to receive all the requests on behalf of.

 app.use((req, res, next) => {
     console.log(req.url);
     next();
 });

app.use The first parameter can also be passed in the request address, which means that the request can be received no matter how it is requested.

 app.use('/admin', (req, res, next) => {
     console.log(req.url);
     next();
 });

2.3 middleware application

1. Routing protection: when the client accesses the page to be logged in, it can first use middleware to judge the user's login status. If the user does not log in, it will intercept the request and directly respond to it. It is forbidden for the user to enter the page to be logged in;
2. Website maintenance announcement: define the middleware to receive all requests at the top of all routes, respond directly to clients, and the website is under maintenance;
3. Customize 404 page.

// Introducing the express framework
const express = require('express');
// Create web server
const app = express();

// Website announcement
// app.use((req, res, next) => {
// 	res.send('the current site is being maintained...')
// })

app.use('/admin', (req, res, next) => {
	// User is not logged in
	let isLogin = true;
	// If the user logs in
	if (isLogin) {
		// Let the request continue down
		next()
	}else {
		// If the user does not log in, directly respond to the client
		res.send('You haven't signed in and can't access/admin This page')
	}
})

app.get('/admin', (req, res) => {
	res.send('You are already logged in to access the current page')
})

app.use((req, res, next) => {
	// Respond to 404 status codes and prompts for clients
	res.status(404).send('The currently visited page does not exist')
})

// Listening port
app.listen(3000);
console.log('Website server started successfully');

2.4 error handling Middleware

In the process of program execution, some unexpected errors will inevitably occur, such as file reading failure, database connection failure; error handling middleware is a centralized place to handle errors.

// Introducing the express framework
const express = require('express');
const fs = require('fs');
// Create web server
const app = express();

app.get('/index', (req, res, next) => {
	// throw new Error('unknown error in program ')
	fs.readFile('./01.js', 'utf8', (err, result) => {
		if (err != null) {
			next(err)
		}else {
			res.send(result)
		}
	})

	// res.send('program execution normally')
})

// Error handling in progress
app.use((err, req, res, next) => {
	res.status(500).send(err.message);
})

// Listening port
app.listen(3000);
console.log('Website server started successfully');

2.5 capture of asynchronous function errors

stay node.js In, the error information of asynchronous API is obtained through callback function, and the error of asynchronous API supporting Promise object can be captured by catch method. How to catch the error when the asynchronous function is executed?
try catch can catch errors in the execution of asynchronous functions and other synchronous codes, but not in other types of API s.

const promisify = require('util').promisify;
const readFile = promisify(fs.readFile);

app.get('/index', async (req, res, next) => {
	try {
		await readFile('./aaa.js')
	}catch (ex) {
		next(ex);
	}
})

3 Express framework request processing

3.1 build modular route

1. Basic code for building route:

// Introducing the express framework
const express = require('express');
// Create web server
const app = express();
// Create routing object
const home = express.Router();
// Match request paths for routing objects
app.use('/home', home);
// Create a secondary route
home.get('/index', (req, res) => {
	res.send('Welcome to the blog Homepage')
})

// Port monitoring
app.listen(3000);

2. Build modular route( home.js and admin.js File in other path):

// Introducing the express framework
const express = require('express');
// Create web server
const app = express();

const home = require('./route/home');
const admin = require('./route/admin');

app.use('/home', home);
app.use('/admin', admin);

// Port monitoring
app.listen(3000);

home.js The documents are as follows:

 // home.js
 const home = express.Router(); 
 home.get('/index', () => {
     res.send('Welcome to the blog display page');
 });
 module.exports = home;

admin.js The documents are as follows:

 // admin.js
 const admin = express.Router();
 admin.get('/index', () => {
     res.send('Welcome to blog management page');
 });
 module.exports = admin;

3.2 get request parameters

Use in Express framework req.query You can GET the GET parameter, which will be converted into an object and returned inside the framework.

 // Receive parameters after question mark in address bar
 // For example: http://localhost :3000/?name=zhangsan&age=30
 app.get('/', (req, res) => {
    console.log(req.query); // {"name": "zhangsan", "age": "30"}
 });

3.3 post request parameters

The third-party package body parser is needed to receive post request parameters in Express.

 // Introducing body parser module
 const bodyParser = require('body-parser');
 // Configure the body parser module
 // Block all requests
// extended: false method internally uses the querystring module to process the format of request parameters
// extended: true method internally uses the third-party module qs to process the request parameter format
 app.use(bodyParser.urlencoded({ extended: false }));
 // Receive request
 app.post('/add', (req, res) => {
    // Receive request parameters
    console.log(req.body);
 }) 

3.4 Express routing parameters

// Introducing the express framework
const express = require('express');
const bodyParser = require('body-parser');
// Create web server
const app = express();

app.get('/index/:id/:name/:age', (req, res) => {
	// Receive post request parameters
	res.send(req.params)
})

// Port monitoring
app.listen(3000);

3.5 static resource access function

Built in with Express express.static You can easily host static files, such as img, CSS, JavaScript files, and so on.

// Implement static resource access function
app.use('/static',express.static(path.join(__dirname, 'public')))

Now, the various files under the directory are accessible.

4 express art template template engine

4.1 usage of template engine in Express

  • In order to make art template template engine work better with Express framework, the template engine officially encapsulates Express art template on the basis of the original art template template engine.
  • Use the NPM install art template express art template command to install.
const express = require('express');
const path = require('path');
const app = express();

// 1. Tell the express framework what template engine to use to render template files with what suffix
//  1. Template suffix
//  2. Epidemic situation of template used
app.engine('art', require('express-art-template'))
// 2. Tell the location where the express framework template is stored
app.set('views', path.join(__dirname, 'views'))
// 3. Tell the default suffix of the express framework template
app.set('view engine', 'art');

app.get('/index', (req, res) => {
	// 1. Splicing template path
	// 2. Splice template suffix
	// 3. Which template and which data are spliced
	// 4. Response the splicing result to the client
	res.render('index', {
		msg: 'message'
	})
});

app.get('/list', (req, res) => {
	res.render('list', {
		msg: 'list page'
	})
})


// Port monitoring
app.listen(3000);

four point two app.locals object

1. Set the variable to app.locals Under object, this data can be obtained in all templates.

app.locals.users = [{
	name: 'zhangsan',
	age: 20
},{
	name: 'Li Si',
	age: 30
}]

2 index.art and list.art The above data can be imported into the file:

//1.index.art
{{ msg }}

<ul>
	{{each users}}
	<li>
		{{$value.name}}
		{{$value.age}}
	</li>
	{{/each}}
</ul>

//2.list.art
{{msg}}

<ul>
	{{each users}}
	<li>
		{{$value.name}}
		{{$value.age}}
	</li>
	{{/each}}
</ul>

3. Rendering on the page

app.get('/index', (req, res) => {
	res.render('index', {
		msg: 'home page'
	})
});

app.get('/list', (req, res) => {
	res.render('list', {
		msg: 'List page'
	});
})

Posted by ThatGuyBob on Fri, 12 Jun 2020 00:59:16 -0700