express-router 解决的问题

  1. app.get('/api/student', (req, res, next) =>{});
  2. app.post('/api/student', (req, res, next) =>{});
  3. app.delete('/api/student', (req, res, next) =>{});

这样就会有很多冗余,请求地址一样就协议变啦,但是app.use() 中的中间件函数在任何协议下的请求都能触发,这俩结合一下不就能节省很多冗余,而且express的路由本身就是中间件函数,示例如下

  1. // 匹配的baseUrl为 /api/student,当满足这个条件就将其交给路由的处理
  2. app.use('/api/student', require('./api/student'));
  1. const express = require('express');
  2. // 创建路由
  3. const router = express.Router();
  4. const { asyncHandler } = require('../getSendResult');
  5. const stu = require('../../services/studentService');
  6. // 获取学生
  7. router.get(
  8. '/',
  9. asyncHandler(async (req, res, next) => {
  10. const page = req.query.page || 1;
  11. const limit = req.query.limit || 10;
  12. const sex = req.query.sex || -1;
  13. const name = req.query.name || '';
  14. return await stu.getStudents(page, limit, sex, name);
  15. })
  16. );
  17. // 添加学生
  18. router.post(
  19. '/',
  20. asyncHandler(async (req, res, next) => {
  21. return await stu.addStudent(req.body);
  22. })
  23. );
  24. module.exports = router;

缺点

expressd.router对不怎吗支持异步,promise的支持非常差,需要将promise的结果转换后才能使用

  1. exports.getErr = function(err = "server internal error", errCode = 500) {
  2. return {
  3. code: errCode,
  4. msg: err,
  5. }
  6. }
  7. exports.getResult = function(res) {
  8. return {
  9. code: 200,
  10. msg: "",
  11. data: res,
  12. }
  13. }
  14. // 将其转换
  15. exports.asyncHandler = function(fun) {
  16. return async (req, res, next) => {
  17. try {
  18. const result = await fun(req, res, next);
  19. res.send(exports.getResult(result));
  20. } catch(err) {
  21. next(err)
  22. }
  23. }
  24. }