问题描述
你怎么样?
这是我的代码:
function login(){
alert("Login Successfully!");
}
以下是我的路线内容的一个示例:
const router = Router();
router.use(
`${routePrefix}/v1/associate-auth/`,associateAuthRoutesV1(router)
);
router.use(
`${routePrefix}/v1/associate/`,JWTVerify,associateRoutesV1(router)
);
app.use('/',router);
问题是: 当我未在一个路由文件中设置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,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)