Express Router呼叫另一条路由时应返回Not Found404

问题描述

你怎么样?

这是我的代码:

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)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...