This article has participated in the third “topic writing” track of the Denver Creators Training Camp. For details, check out: Digg Project | Creators Training Camp third is ongoing, “write” to make a personal impact.
Middleware literally means anything that sits between one layer of software and another. Express Middleware is a function that executes during the life cycle of each request for an Express service.
Experience Express Middleware
Let’s take a quick look at middleware. First, create a project and go to the directory to execute it
npm init
npm install express --save
Copy the code
Create a server.js with the following contents:
const express = require('express');
const app = express();
app.get('/'.(req, res, next) = > {
res.send('Welcome home');
});
app.listen(3000);
Copy the code
Start the service from Node server.js, visit http://localhost:3000, and you should see “Welcome home” in your browser.
(req, res, next) => {
res.send('Welcome home');
}
Copy the code
The anonymous function in the example above is a middleware function that terminates the request and returns a welcome home string to the client.
Format and usefulness of middleware
Express middleware functions can access request objects (REq), response objects (RES), and the next middleware function. The next middleware function is usually represented by a variable named next.
function middware(req, res, next) => {
console.log(req);
next();
}
Copy the code
If a request matches more than one middleware function, each middleware will execute in sequence until the request ends. As shown in the figure below.
Of course, during each middleware process, the request can also be terminated by itself, so that the next middleware function is not executed.
The middleware features can perform the following tasks:
- Execute any code.
- Make changes to the request and response objects.
- End the request-response loop.
- Call the next middleware in the stack.
If the current middleware function does not end the request-response loop, then next() must be called to pass control to the next middleware function. Otherwise, the request will be suspended.
With middleware, we can organize our code more orderly.
Classification of middleware
According to the usage scenarios of middleware, it can be roughly divided into the following types of middleware
- Application level middleware
app.use
- Routing level middleware
router.use
- Express Built-in middleware
express.static,express.json,express.urlencoded
- Error handling middleware
app.use(err,req,res,next)
- Third-party middleware
bodyparser,cookieparser
Application level middleware
Simple log example log.js:
const express = require('express');
// custom middleware create
const LoggerMiddleware = (req,res,next) = >{
console.log(`Logged ${req.url} ${req.method} -- The ${new Date()}`)
next();
}
const app = express()
// application level middleware
app.use(LoggerMiddleware);
// users route
app.get('/users'.(req,res) = >{
res.json({
'status':true
})
})
app.listen(3002.(req,res) = >{
console.log('server running on port 3002')})Copy the code
Start the node log.js service and access localhost:3002 localhost:3002/users.
server running on port 3002
Logged / GET -- Sat Aug 21 2021 11:54:28 GMT+0800 (GMT+08:00)
Logged /users GET -- Sat Aug 21 2021 11:56:18 GMT+0800 (GMT+08:00)
Copy the code
Routing level middleware
Router-level middleware works the same way as application-level middleware, except that it is bound to an instance of express.Router().
const router = express.Router()
Copy the code
Load router level middleware using functions like router.use() and router.post().
const express = require('express');
const app = express();
const router = express.Router()
router.use((req,res,next) = >{
console.log("Time:".new Date())
next()
})
router.get("/user/:id".(req,res,next) = >{
console.log('Request URL:', req.originalUrl)
next()
},(req,res,next) = >{
console.log('Request Type:', req.method)
next()
},(req,res) = >{
res.json({
status:true.id:req.params.id
})
})
app.use('/',router)
app.listen(3000.(req,res) = >{
console.log('server running on 3000')})Copy the code
Server running on 3000 Time: 2021-08-21T04:02:19.781z Request URL: /user/1 Request Type: GET Time: 2021-08-2T04:02:24.002z Request URL: /user/123 Request Type: GETCopy the code
Built-in middleware
Express has the following built-in middleware capabilities:
- Express.static provides static assets, such as HTML files, images, and so on.
- Express. json uses the JSON payload to parse incoming requests. Note: For Express 4.16.0+
- Express.urlencoded parses incoming requests using URL-encoded payloads. Note: For Express 4.16.0+
Example: The following action defaults public to a static resource directory and does some configuration.
var options = {
dotfiles: 'ignore'.etag: false.extensions: ['htm'.'html'].index: false.maxAge: '1d'.redirect: false.setHeaders: function (res, path, stat) {
res.set('x-timestamp'.Date.now())
}
}
app.use(express.static('public', options))
Copy the code
Error handling middleware
Express JS comes with default error handling parameters. The error handling middleware function is defined in the same way as any other middleware function, except that the error handling function has four parameters instead of three:
app.get('/my-other-thing'.(req, res, next) = > {
next(new Error('I am passing you an error! '));
});
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke! ')})Copy the code
Third-party middleware
In some cases, we add some extra functionality to the back end. Install specific third-party middleware, and then load it into your application at the application or router level. Such as bodyparser cookieparser. Example:
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/'.function (req, res) {
// Cookies that have not been signed
console.log('Cookies: ', req.cookies)
// Cookies that have been signed
console.log('Signed Cookies: ', req.signedCookies)
})
app.listen(8080)
Copy the code
Visit curl http://127.0.0.1:8080 –cookie “Cho=Kim; Greet=Hello”
Cookies: { Cho: 'Kim', Greet: 'Hello' }
Signed Cookies: [Object: null prototype] {}
Copy the code
The last
Through the above learning, I hope to help you. Original is not easy, thank you for reading, welcome to like collection.
Here are my previous articles, if you are interested, please continue reading.
- Tanabata senior single 🐶 guide, because of the wrong design mode
- Read screen size, resolution, PPI, device independent pixel, Retina
- How many front-end 40K high-paying jobs are there, and where are they distributed?
- The front-end interviewer asked, “Can you build a rocket?” I said, “Yes.”
Reference thanks
- writing-middleware
- using middleware
- How Node JS middleware Works?
- Build and Understand Express Middleware through Examples