简体   繁体   English

Express 路由器在应返回 Not Found (404) 时调用另一条路由

[英]Express Router call another route when should return Not Found (404)

how u doing?你好吗?

Here is my code:这是我的代码:

const router = Router();

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

Here is an exemple of my routes content:这是我的路线内容的示例:

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

The problem is: When I don't set the root('/') in one of routes file, Express find the next file with the same method in root ('/').问题是:当我没有在其中一个路由文件中设置 root('/') 时,Express 在 root ('/') 中使用相同的方法查找下一个文件。

How can I configure to return 404 when there is no route specify?当没有指定路由时,如何配置返回 404?

use http-errors module and create 2 middlewares, the first for error handler, and the second for endpoint handler:使用 http-errors 模块并创建 2 个中间件,第一个用于错误处理程序,第二个用于端点处理程序:

error handler in errorHandler.js 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

endpoint handler in endpointHandler.js 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

then in your main js:然后在你的主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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM