javascript - 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?
解决方案
使用 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)
推荐阅读
- c++ - Qt 应用程序未定义对“gst_app_src_push_buffer”的引用
- javascript - 打字稿导入不起作用,因为类在 dist 文件夹中
- google-data-studio - 谷歌数据工作室:推荐的公开模式的方法?
- node.js - 无法安装反应脚本 E403
- python-3.x - Telling the python interpreter to take the current path for resolving relative directories
- python-3.x - Pandas 对较大拆分字符串中的单个元素进行分组
- java - 我有一个单例的连接池类。当我尝试在我的 DBDAO 类中调用它时出现问题并创建 2 个实例
- mysql - MYSQL 中的 COALESCE + SUM 计算不正确
- javascript - 如何在java脚本中找到修改数据的代码
- windows - 指向 SMB 共享的链接挂载文件夹而不是卷