使用中间件
Express 是一个路由和中间件 Web 框架,其自身功能最少:Express 应用程序本质上是一系列中间件函数调用。
中间件函数是可以访问应用程序请求-响应周期中的 请求对象 (req
)、响应对象 (res
) 和下一个中间件函数的函数。下一个中间件函数通常由一个名为 next
的变量表示。
中间件函数可以执行以下任务:
- 执行任何代码。
- 更改请求和响应对象。
- 结束请求-响应周期。
- 调用堆栈中的下一个中间件函数。
如果当前中间件函数没有结束请求-响应循环,它必须调用 next()
将控制权传递给下一个中间件函数。否则,请求将被挂起。
QgOlzqXPvYC3exD3uSTSlKdnt/cGGEdLG1BXw3kiQ4C/VlyUQJEF3IxjdU6XyL8+sfcJ6bLiJAurp2UkUWQp0Q==
- sSllqoBfNAAx/RMfjku1BcWmKzAp61sHvyYOUnCutuo905FlC12bSZB/dRH8iGK5P/7nCEwRbOhZVXn6dEgfQqwynElXIb1z6X6hRP3KOvgrXuibDA+6y8bOdOHEIzJBrI7JrFdgQhor36JL+ZrIUiyrbDfAyl5hlXMNIM2wq9DIZBZ475mT3a+NY6zMz/ZHGOK/NaI7KLPhHzLet9Erujd9bcp4X+7yM1UZTino+z3DFgJi6horQSH8Q9XGZrjRXJvhEg88RQ68r2N3MEomI79+Sppx0aVH6VItvVb1Fprp3AM4aAN0tBdQroG2t9z7kvA3i4i/VxIci7gqYw5eNmBPa1T/BUjJIlWMbXKiSBZvDZHTvVsQGk4kDGn1xttSetru+l8cBd7hufavBvdGXLHzq8/td00Bt9qOgZqtG+afL7iBCaeIs+NyztYtjN5hPDHQOjD1jX8DyVgu0RaWwDaO5H/URz1KDBxLHYQnGyT1gFKM/vxy1EoH8D81kqB1Yfm8cbECe6/63D+NXWtsoQ==
zZhl1uusrkXR2q65DmYF7hrBGXx/wcbi3wWoXp7sFsjkf/U3KQSma34+Lv+/YPARQoMgOlVPgbzY31zAYK8rWhESFu7vhK9oFDg/hZyAfsTe4RjIghjYcmwknQL4oGZ4NIqb54EgjFCbYaM1/y+/ySK+fKlOFp5trU27yLAj6fH/i+dxOlYDEX9c1MGVv+fr67a8EDXmll+AxhC8lr5PhryWjaOPJ8LFM0g2bRPfKSqqGY59E/EmcFkHlpb64aOU
应用级中间件
0FKCWGlky/ljLV3hs4EVA0bE+SOmGlJckkP7Qk6r3qlQwISRr7bkd6BCVwbS/tWlS6dqucLPHFwTQnI3SJ3HGETkXhkHFAUcC8XqXlTfzvewaz5b9bw7OyOW4leiI8v5wa6eIgB4d45Kv3FSxjp/4j7JH7fu01re11UD8CXjykWIs8l634LmnlrNAs6weILeV+BUwaBFZ+P6lCuK5qQ0ta1eOrI+pXlqgUTJo2hRlDw3IqDTOrpZMk32X+P4sGQdw5OH5jB7pTCsQ6w1ehaEknIYI2V+9UcLeWlZhNJ89wuMadneVZibPlX0sb4h8Z1/1z9Tlrdem1l8JSfOB+dw7hCov/5IH9uo87vuQx0T06tigRkWs0mLLvEwR45qOATv
SnbNr97GFr/Wq0LtbLptouRbHZXhFkZI2AM0kC9xjQ4CiBxDF+pzSlJIkEieNoplzMOQR/BTVXDsKyIJL5J9u5t9nDDGKyQl16mgRLV4w51Qrzprz+l+cbkfQaQDBcpdNyProYa43TLDciY09ypm8tMpHli3nwccyiV+nO5oBQM=
const express = require('express')
const app = express()
app.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})
/rBxsPywT/GB3mhzagabbsnIOLG6asX+AOaPIGYcR+e/0ECiE3myGi5P0J3iUS4SVPAKAjv86CW+0XxVqmh+kJsgitC/ZnBQlLkCBlcWTpQDeT1uidIzI2bhPm0yk/eIEwPy1jDoGuBKC45MEr9Q6x/XLqtY6tdtQRTTc9tdm8MIKmeWtRlgta8wAT6BUF3/EuYomSpLJJH+bGvEvzAjSWVzLuvdd18S9gWAG4+fvlCKdAwMV1X+pdmLzVR+SW5g
app.use('/user/:id', (req, res, next) => {
console.log('Request Type:', req.method)
next()
})
/rBxsPywT/GB3mhzagabbn+NkUQ7g5hgnCI219RS6fivmMHsoUb6Oz8Vj1yarGDpy5Be8aLbjC2ByOw4OFBCD6z1AX36iLkuyXFPmhEvxfzFGtHs21zdnSUIIKBaZaDaGTR2WpQdlC7H6y0F3j9QlGeNMdI5A5J4Szrc2dPArHv2t/nPb6VS0MhW8ATE98rk
app.get('/user/:id', (req, res, next) => {
res.send('USER')
})
LwN4yHgyjCV/HyJRJCuYBu3+sE9p/v/gtDYkvX3eyoOHfwABmu01G1QVT9uPMEQhztOgwVkd61hPjINbrxoJTeclPnlw6PKRJEy4rJqWXWXb+xAbo4rGmTHZ/qxRbg1uKFz0VJutByIehTC5rwf25uWz8oM8EpHvZeKLxMk5fjULUH+0bLUY09DqENnCeWsOG/gNV4n4x4JLbkfcpDv+USODE2QlTUpUEICfzle+/TXFy/2aBGxbS8v69eNsLyDCGfehQDuClzxVxHj6JkEQJXVjgM0jVFB12Wb45bsQaoI=
app.use('/user/:id', (req, res, next) => {
console.log('Request URL:', req.originalUrl)
next()
}, (req, res, next) => {
console.log('Request Type:', req.method)
next()
})
K+axwztuIWHzLf2FydF5IpOP02cc3H5STlvDTDVpcfoWf1U1X/myUhEm0a3Ov+OMgBV/yAUoljY2TBjcRukoBttZrseiormzSIFuIK7nDEKCe6Vx51ROPQKifrBuWEQSSuX9cvljqjkB9j+Ixu46bRwLjKB9KM8pXt8fMtSLbkFHGuJy8qc5mtfDbO/+soEqoq3QKN4OnP2PaBM4xaWQ/CgeEobIZBAphUGQoZrcEq87vUGbyGovwFRLSyrjjZOhBdHLX2lZfIR8DeA3edfpshhlwYdSR29kEMHnjBxR7tPAHSDc/84G3/JTk5jROOTvZj+oV0VvfzQJ19lf77ylALeFEWcRc8KGqm3I2OnaKhg=
SnbNr97GFr/Wq0LtbLptoudkB2trw9ajLKJSeWDuoHGjQUw7E/acbMUzUr2JDMrUp/Pb3NY+4end437nkWJmNZd2PzqEpHbskLkRxBf3U569yMwyT93tvsBDVxvsn8s93sxfEXQ2OXVBuH3m6lzykw==
app.get('/user/:id', (req, res, next) => {
console.log('ID:', req.params.id)
next()
}, (req, res, next) => {
res.send('User Info')
})
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', (req, res, next) => {
res.send(req.params.id)
})
LG+88epeCRNZVBwcPuJcTch2f64PxEWFGbVpuWfgWFVtnJU2wZcdgn3SQI+Yd1r2j64VXQAktX80Ue/YDc4BCWP2E3Kd46adzOMxbhCBtUoKPcGIETpLCuvXv2UrT7Jx+DqtuWVmlhtpF5dW/q5mJPS5qFUNWsWlvqnhE9mQMgkBhnyjiJJxzHbdIumBeTpS5dlx9vs9dz/w1wDSPkf24B/TdFCt07XYu6iTVnYHB+nNM1ah1Ej3fNYNV5sX+b+UM5+4+8xtgLJFj8FsbSxTFy0OLaPpdN+1c8L3c2IWyFFEWY33FzDqqHcM4JD9c+xQ9IwaffZWyG8IY5V7FfBSIpXhfHlgrIaa4Hj/mANAg0Xdp0vlwT+uVGK2sDQR7/5RYWynxUy/VUq6C7eqd2UU0g==
SnbNr97GFr/Wq0LtbLptoudkB2trw9ajLKJSeWDuoHGjQUw7E/acbMUzUr2JDMrUp/Pb3NY+4end437nkWJmNZd2PzqEpHbskLkRxBf3U569yMwyT93tvsBDVxvsn8s93sxfEXQ2OXVBuH3m6lzykw==
app.get('/user/:id', (req, res, next) => {
// if the user ID is 0, skip to the next route
if (req.params.id === '0') next('route')
// otherwise pass the control to the next middleware function in this stack
else next()
}, (req, res, next) => {
// send a regular response
res.send('regular')
})
// handler for the /user/:id path, which sends a special response
app.get('/user/:id', (req, res, next) => {
res.send('special')
})
A0NhxVM2+Qf5mJa3aw/+WQSmp/0Vx8k5jgIyeHWU5JcBL2wKUVbE7bVtGSnM2zuleIJTwNkYYBIlZ14UiNiTww==
SnbNr97GFr/Wq0LtbLptokOFWEta0CN2Cdn9TX4zoqD9J38EgyYVSiV1Y0Cj5GaxN5QAjDeydHgpq5vsgOydoZKGiwzOlI3eRmgVKBN25iveIjnK/uqvCT1WkOjrOoZP1TpBo7CPhNhUkwlnFJO2E3Qjo/y5aihG58afdCLX+8I=
function logOriginalUrl (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}
function logMethod (req, res, next) {
console.log('Request Type:', req.method)
next()
}
const logStuff = [logOriginalUrl, logMethod]
app.get('/user/:id', logStuff, (req, res, next) => {
res.send('User Info')
})
路由级中间件
VG2cEToE1syTFjYa8VCTO8wUUwMCFHOecIe/Pt8ZHe5nT57I4aUX4ddofjEZwzqGSIalTzJjOVBZ9WEEvzjipMbr1rgZbfG+lepaZEqV5DwvnygbIxaNFAegtN9dySYkbDfJS5+zjPXzL66ncUTI7TmpFTuTaQRn0Hvmokm3LoA=
const router = express.Router()
caRPhImnhXeyvZvBhMPMnINZ3KwjLuuxlPQsP7DYHdZ4DCEgDEyDNpqDEoNZKYHy9tVeoQP6ncIlxm+iX1QfxFsQI3cdUXmfFMUjGfpPoFr1fezq6JBOVOOQZ3YyYsbgWZc26adTRNOF06KzJNDAXg==
zRuaN1zOP6hMUaJiYDcHbo/vNKazBQysl25FdtTZxyycSBIPiF5mngoiMuZFcAqHYZObjsM+pFyCLyInduf+BLI/CtBjgBPZHRzQwt36SrXatvCwBQDoODxIv0qCmculHQDD69Dj+H7urjUqV3wiYzhtXCMnUpXwSbcsE1ei12c=
const express = require('express')
const app = express()
const router = express.Router()
// a middleware function with no mount path. This code is executed for every request to the router
router.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})
// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.use('/user/:id', (req, res, next) => {
console.log('Request URL:', req.originalUrl)
next()
}, (req, res, next) => {
console.log('Request Type:', req.method)
next()
})
// a middleware sub-stack that handles GET requests to the /user/:id path
router.get('/user/:id', (req, res, next) => {
// if the user ID is 0, skip to the next router
if (req.params.id === '0') next('route')
// otherwise pass control to the next middleware function in this stack
else next()
}, (req, res, next) => {
// render a regular page
res.render('regular')
})
// handler for the /user/:id path, which renders a special page
router.get('/user/:id', (req, res, next) => {
console.log(req.params.id)
res.render('special')
})
// mount the router on the app
app.use('/', router)
AnV0YgF5+5wkq/LiTv5C/cDVrDM2xI0bCRv/g9VnH9nhx8qh94yJG6OiwtCF2ItgQ5gcMI1aJ1EO+62a2lGpNxgeS2SUa0MgcABNRB9hW8p5RIEUQKutc+GqoG+eerpdP/CA0wljBWYAqFWBkjIeXpyH6U9HVOP9O45d7vIzn6w=
SnbNr97GFr/Wq0LtbLptoudkB2trw9ajLKJSeWDuoHGjQUw7E/acbMUzUr2JDMrUp/Pb3NY+4end437nkWJmNZd2PzqEpHbskLkRxBf3U569yMwyT93tvsBDVxvsn8s93sxfEXQ2OXVBuH3m6lzykw==
const express = require('express')
const app = express()
const router = express.Router()
// predicate the router with a check and bail out when needed
router.use((req, res, next) => {
if (!req.headers['x-auth']) return next('router')
next()
})
router.get('/user/:id', (req, res) => {
res.send('hello, user!')
})
// use the router and 401 anything falling through
app.use('/admin', router, (req, res) => {
res.sendStatus(401)
})
错误处理中间件
skL8udwtYtE3+6xZV4WOvJdEau8PvFBNpP+gY3qjP+FWwaHAWKUYXyrxxFQFY5nirkfe3ma3eTWNkKGYyrZsXDrSYTnAAEWvtKAsLJuTPJVcdHFgj/HBgVUPGB0iSsNzDi1HmXia/tK/lbYzfmW2oZVNe9e5utj6pZlSqTAozuHL4VUElPBlb5bODN4ICfHVmoj8jEVOmIsGPAE69LUhHEod/oFlh03bxMjZZIA/lzxSfLvHw9zd/w1gtI+B0DsZBj/iebxucULJlZtulccqrpSau6X+zvVytPyjeQWWqayHBu51c9+gm/Qmg3gxBaA0KIHURBgVj91Y7McBTUpdpdq3Olf6fHcFmrczlnwzBMphCm84DfZPNywREH+Mjqidx0NlSq6i1lawUxoHppJOSQ==
qjC+m9KNSlxmrFpjN11PNVN8YRdod9JT6NJ71u29C/AtIB2gkj76+iUL3v6ioHXhRXtIdj0OVaZ+YwDHMTPnPx8DNT5yxMyPlR258/OpA+nbZ41S0RjZE5dRuKiC1D5vKdAIR5EY9n1KM6YTijird9vRsvh6nvgo0IT+mbtrL89KfE4mqH352bJBIbey4srid1XEXWirsN4V3hmcEW0e7J8inJmSmcp3ZTfHR1bA3e3jMAquhA7ElCVg5XhbKCWj
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
9Cx7oA+RuEpi5NKkRLJhYdLXgP7HAOTHYkom/l4kHp/JDBRinSu19HLJI+SxsJOuMacveREefC1ncSTIUH0aQ8VnlC0tf6rO6myaYwf+YR3d36jbT2F4ovPbCgN/HLmfxapLEJesfhrOUGmKKiYsPHARq3QzdlX1KXrDWJ7f5aw=
内置中间件
likia1vaLDrSBkdk8jgcb6Wscb2h8xlTQrwDzj5x1kw25LA90qHps2A7kd0KTCJ15R+BxcEve6aG1Cd0/gRoJwmsVh3NqaoJcWO8NZEyZKBxkC9y32myfhvTu97FEjTmS8lqTnC74JDS6XhUjhAFTbW93Nd/jjO0L3wJYGvSfcZLROrrgCMm0vYEIGjD9FXwWRn07boSbq79lxvhQ+ht69Tu65RcZ3VYu5pEmsSx0GpYHXS9Jj6ls0BVPg3Y0H1IiW4BfVGy//hZoRlbjh2YH9mwubSk55liSengydrZkktux9kFdJzjx3O7qCAipqKcW5nmMyhcBVvbKtzH1vg02k1ECH5wnIx3sZbgXRx46JU=
jp/5KESBIEUtXfFDTwZ81C/sgplnZavg2eLfi/GBqzP3mbdZTy6moVERynBRC4hC
- sSllqoBfNAAx/RMfjku1Baj5tdpSSmHgd22LkgmJDLPROlazqBN95tDZhOCUuOigj5oeiiyeVSCFsaoJF/jyNOvjYqMVR2hFXFtRIjwljl3n0L3YsZHs7clq+SLXIiThWhKBe8BmHxGY6nskNCKD+F9eW41LUoI1iMmVNPiNtYgD/z4kR/qb3Kw8xhZQNDlL1CDLB/s12XopuJQA0NlJbkBW4orLOS9Fw+6FmMRUw4bsqUoWRhqNG4wAvjSSvKDDw5Kim0x5zro38jZzhqTzuLdtqCKPPPGwB2nFr5vJd72db3ufs2vOBhA5ItdP6C++lI8Zizqysh88/ISUnk/B6rDfWSQjZx6GK4VvvUJgVvaWVdEoosY7aBEwK2BOe749S/ffZ4iylXvGSrSMSHsZTjXzMFPKAJNI9sjNUQ9+QXMOoRRDJh7fu7nedeBCxdrOIUKs5CAxYEjQOclsWYv2qCC+PcEDsW7uXYZULE9byu2hzhTa+S8GMJ2lvY/EZpZcxFfra8Wo4UPvBMsZbJ0TqpTtfsuI/9gFQPN6JNOscOc9CQNuFGlPoo62YrU3yw5SnIzQz4lLqMbTFyTuiMZGaVZRMaPj470XGYG3rhmUUEVfae2a36YGtlPH1YWKkF0N
第三方中间件
MMYGEsOQVtz+fS96fueWyf6Es9iY73w11E/PXbQuXTDAlwb/b515updj4T91Wp9pNtZkkeBCod+Pr3tSOQfrqw==
YAamgt+G12gAZbW5oVLFBKqvS+YbevkL7X1f691otWareNe3DY6R1Ucs4SLr+SG9HwXAxmIf+LqGP64/EJldbToebarABJHuNy/BvFb5ZcmKAWkFcF3qn0uL0rrHEnsCqDodE9QuZqCMR9ZkZU0ptnjmH8XiK9b84GnCtYt+Vn8=
LYO5TJO3IoDGbH+GbpJjlV1h9377gF+C3FrhwSF1qnG9UegZMmFiiItUU69giR214A6Nz3+q8FzMAQH6KjA+lSvMNmdNBSVyxlrbmJn79EowMDuclRMXMarpdT5fvBVg
$ npm install cookie-parser
const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')
// load the cookie-parsing middleware
app.use(cookieParser())
1Hejh7x0pOBW97WgA6MKAF7eh32SY2HdrMTn6gNK55TreuMohEY9sPTAzus19z8BeIdybZBOjckT0N1iwEKilZLVnZuE4COxuxgLjxZVzuTInBl8MuWPPA42bfhTlS2jVzslpWGKHh5FpIz9juVH4Oxt0Pna/O+T6wtaGPIQV0HcJe23wi5SskVQ0ukaRi+GkOdT8EJwwFq/NIOAdNbF3A==