首页 > 解决方案 > Express 路由器在应返回 Not Found (404) 时调用另一条路由

问题描述

你好吗?

这是我的代码:

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?

标签: javascriptnode.jsapiexpressexpress-router

解决方案


使用 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)

推荐阅读