Copyright notice: This article was first published on my personal website Keyon Y, please indicate the source of reprint.

Project address: github.com/KeyonY/Node…

The logical processing of Express is divided into two parts: forwarding back-end interface and middleware

Forward the back-end interface

The interfaces provided by the back end fall into two categories:

  • The data interface used to render the page
  • The request interface for the front-end part to send ajax requests

Data interface

This is the page that the link to the URL can access.

Router.get () is used to register the route. In the route, axios is used to access the back end to get the page data response. Res.render () is used to return a custom object, and the response is passed to the puG template page as the property of the object. Feel free to use Response in the PUG page.

Github config/routes/default.js

The router / / front page. Get ('/', addUser, (req, res, next) => {
	axios.all([
		axios.get('/Api/Carous'),
		axios.get('/Api/Cars/Top10', {params: {page: req.query.page || 1}}),
	])
		.then(axios.spread(function (res1, res2){
			config.throwError(next, res1, res2);
			var page = req.query.page || 1;
			res.render('Default/index', {
				title: config.title('home'), keywords: config.keywords, description: config.description, menuNav: 0, carList: res1.data.Data, top10: res2.data.Data.slice((page-1)*3,page*3) }); })).catch(e => { config.renderError(req, res, e); })});Copy the code

Request interface

Is the interface through which the front-end sends Ajax requests.

The difference with data interfaces is that the middle tier does only two things:

  • Using AXIos, forward requests from the front end to the back end
  • Use res.send() to forward the response from the back end to the front end
// get request router.get('/User/Role', (req, res, next) => {
    axios.get(config.origin + '/Api/User/Role', config.axiosHeaders(req, { params: {role: req.query.role} })) .then(res1 => { res.send(res1.data); }).catch(e => { config.sendError(res, e); }) // post request router.post('/User/SendRequest', (req, res, next) => {
	axios.post(config.origin + '/Api/User/SendRequest', { userID: req.body.userID || null, requestID: JSON.parse(req.body.requestID) || null }, config.axiosHeaders(req)) .then((res2) => { res.send(res2.data); }).catch((e) => { config.sendError(res, e); })});Copy the code

Post requests cannot read the request body directly, requiring the Body-Parser dependency to be installed

NPM – I save the body – parser

And mount the dependency in app.js

app.use(bodyParser.urlencoded({extended: false}));
Copy the code

Gets the parameters in the front-end request

There are three cases:

  • Gets the parameters in the route with parameters
router.get('/Cars/:id', (req, res, next) => {
    axios.get(config.origin + '/Api/Cars', {params: {role: req.params.id} // req.params.id get parameters in url}))... })Copy the code
  • Gets the parameters of the GET request
// Such as request /Cars/Search? q=tobi router.get('/Cars/Search', (req, res, next) => {
    axios.get(config.origin + '/Api/Cars/Search', {params:} {the car: the req. Query. Q / / the req. Query. Q gain parameters}))... })Copy the code
  • Gets the parameters of the POST request
router.post('/Cars/Search', (req, res, next) => {
    axios.post(config.origin + '/Api/Cars/Search', {car: req.body.name // req.body.name get parameters in the body}))... })Copy the code

Post requests to forward an array object

Express post request to retrieve an array from the client. If an array is directly posted to the client, express cannot retrieve the array. The array needs to be serialized on the client and deserialized in the middle layer:

// client $.ajax({url:'/Api/Mas/SendInfo'.type: 'POST', data: {userID: userID, requestID: json.stringify (selected)}, // serialize success:function (res) {
		log(res);
		if(res.Status == 0){
			$thisModal.hide();
			$('#modal_cds').show(); }}}) // middle layer axios.post(config.origin +'/Api/Mas/SendInfo', { userID: req.body.userID || null, requestID: JSON. Parse (the req. Body. RequestID) | | null / / deserialization}, config. AxiosHeaders (the req))Copy the code

The middle tier does not pass attributes that might not exist

Never pass a property in the middle that might not exist!

Never pass a property in the middle that might not exist!

Never pass a property in the middle that might not exist!

Important things say three times, otherwise appear the following bug do not know where to find.

(node:20352) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property ‘data’ of undefined

The middleware

Express is a web development framework that is minimalist in its own right, entirely composed of routing and middleware: essentially, an Express application calls various middleware.

Middleware is a function that accesses request objects (REQ), response objects (RES), and Middleware in the request-response cycle of a Web application. A variable normally named next.

Middleware features include:

  • Execute any code.
  • Modify the request and response objects.
  • Terminates the request-response loop.
  • Call the next middleware in the stack.

If the current middleware does not terminate the request-response loop, the next() method must be called to hand control to the next middleware, or the request will hang.

Express applications can use the following middleware:

  • Application-level middleware
  • Routing level middleware
  • Error handling middleware
  • Built-in middleware
  • Third-party middleware

Middleware can be mounted at the application level or route level using optional mount paths. Alternatively, you can load a series of middleware functions simultaneously to create a sub-middleware stack at a mount point.

Request objects are processed using routing level middleware

var addUser = require('.. /.. /middleware/addUser'); . router.get('/Car/List', addUser, (req, res, next) => {
    ...
})
Copy the code

AddUser (middleware) is a method that accepts req,res, and next parameters in the route. It must be **next(); ** ends the code, thus passing the function pointer from addUser to (req, res, next) => {… }.

With middleware, cookies in the request header can be retrieved to validate user login information

To obtain the contents of cookies, you need to install the cookie-parser dependency

NPM I – save cookie – parser

In app.js, mount the dependency and use it.

app.use(cookieParser());
Copy the code

Error Handling middleware -Error Handle

Note the mounting order of Error Handle. It is generally mounted under app.use() and placed last. Please refer to app.js in the Second Node Mid-tier Practice (ii) — Building a Project Framework, or check out the Github project code app.js.


Continue to pay attention to the other articles in the series of Node middle layer practice (1) — NodeJS based on the full stack of Node middle layer practice (2) — Build project framework Node middle layer practice (3) — Webpack Configuration of Node middle layer practice (4) — template engine PUG Node middle Layer practice (5) — Express-middle layer logic processing