express-router 解决的问题
app.get('/api/student', (req, res, next) =>{});
app.post('/api/student', (req, res, next) =>{});
app.delete('/api/student', (req, res, next) =>{});
这样就会有很多冗余,请求地址一样就协议变啦,但是app.use() 中的中间件函数在任何协议下的请求都能触发,这俩结合一下不就能节省很多冗余,而且express的路由本身就是中间件函数,示例如下
// 匹配的baseUrl为 /api/student,当满足这个条件就将其交给路由的处理
app.use('/api/student', require('./api/student'));
const express = require('express');
// 创建路由
const router = express.Router();
const { asyncHandler } = require('../getSendResult');
const stu = require('../../services/studentService');
// 获取学生
router.get(
'/',
asyncHandler(async (req, res, next) => {
const page = req.query.page || 1;
const limit = req.query.limit || 10;
const sex = req.query.sex || -1;
const name = req.query.name || '';
return await stu.getStudents(page, limit, sex, name);
})
);
// 添加学生
router.post(
'/',
asyncHandler(async (req, res, next) => {
return await stu.addStudent(req.body);
})
);
module.exports = router;
缺点
expressd.router对不怎吗支持异步,promise的支持非常差,需要将promise的结果转换后才能使用
exports.getErr = function(err = "server internal error", errCode = 500) {
return {
code: errCode,
msg: err,
}
}
exports.getResult = function(res) {
return {
code: 200,
msg: "",
data: res,
}
}
// 将其转换
exports.asyncHandler = function(fun) {
return async (req, res, next) => {
try {
const result = await fun(req, res, next);
res.send(exports.getResult(result));
} catch(err) {
next(err)
}
}
}