【问题标题】:Express Router call another route when should return Not Found (404)快速路由器在应返回 Not Found (404) 时调用另一条路由
【发布时间】:2023-04-07 02:45:01
【问题描述】:

你好吗?

这是我的代码:

const router = Router();

router.use(
    `${routePrefix}/v1/associate-auth/`,
    associateAuthRoutesV1(router)
  );
  router.use(
    `${routePrefix}/v1/associate/`,
    JWTVerify,
    associateRoutesV1(router)
  );
app.use('/', router);

这是我的路线内容示例:

  router.post('/', async (_req, res) => {
    res.send('OK');
  });

问题是: 当我没有在其中一个路由文件中设置 root('/') 时,Express 在 root ('/') 中使用相同的方法查找下一个文件。

如果没有指定路由,如何配置返回 404?

【问题讨论】:

    标签: javascript node.js api express express-router


    【解决方案1】:

    使用 http-errors 模块并创建 2 个中间件,第一个用于错误处理程序,第二个用于端点处理程序:

    errorHandler.js 中的错误处理程序

    function checkError (err,req,res,next) => {
      return res.status(err.status || 500).json({
        code: err.status || 500,
        status: false,
        message: err.message
      })
    }
    
    module.exports = checkError
    

    endpointHandler.js 中的端点处理程序

    // endpoint handler in endpointHandler.js
    const isError = require('http-errors')
    
    function checkRoute(req,res,next) +> {
      return next(isError.NotFound('invalid endpoint')
    }
    
    module.exports = checkRoute
    

    然后在你的主 js 中:

    const app = require('express')
    
    const checkError = require('./errorHandler.js')
    
    const checkRoute = require ('./endpointHandler.js')
    
    const router = Router();
    
    router.use(
        `${routePrefix}/v1/associate-auth/`,
        associateAuthRoutesV1(router)
      );
      router.use(
        `${routePrefix}/v1/associate/`,
        JWTVerify,
        associateRoutesV1(router)
      );
    app.use('/', checkRoute, router);
    
    app.use(checkError)
    

    【讨论】:

      猜你喜欢
      • 2016-07-22
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多