express
官网:https://www.expressjs.com.cn/
基本使用
const express = require('express');
// app实际上是一个函数,用于处理请求
// express内部使用了http模块
const app = express();
let port = 9527;
app.listen(port, () => {
console.log(`listen ${port}`);
})
中间件概念
1.当匹配到了请求之后交给第一个函数处理如若需要交给后续的中间件需要手动执行next()
2.中间件处理细节
2.1.如果后续没有了中间件,expres发现相应没有结束,express会响应404
2.2.如果中间件发生了错误,不会停止服务,会寻找后续错误的中间件,相当于调用了next(错误对象)
app.get('/news', (req, res, next) => {
console.log('handle3');
next();
})
自行书写的错误中间件
app.use('/news', require('./errorMiddleWare'))
//处理错误中间件
module.exports = (error, req, res, next) => {
if (error) {
const errObj = {
code: 500,
msg: error instanceof Error ? error.message : error
}
res.status(500).send(errObj)
} else {
next()
}
}
app.get('/news', (req, res, next) => {
console.log('handle1');
// res.send('123');
throw new Error('abc')
//相当于调用next(new Error('abc'))
})