同一路由器上的多个.use()会导致覆盖回调

Multiple .use() on the same router are causing overwritten callbacks

本文关键字:回调 覆盖 use 路由器      更新时间:2023-09-26

我使用一个名为consign的模块,一次在目录中包含几个不同的模块(而不是有一堆require语句)。在这些模块中,我一直在路由器文件的顶部为每个端点设置挂载路径,以免在整个文件中重复多次。然而,托运将相同的路由器传递给这些文件中的每一个(这通常应该是好的),并且如果任何文件中的路径相同,则挂载路径实际上会通过use()方法被覆盖。我会尽力用最好的方式来展示。

/线路/api.js

var express = require('express');
var router = express.Router();
var consign = require('consign');
// get all routes inside the api directory and attach them to the api router
// all of these routes should be behind authorization
consign({
  cwd: 'routes'
})
  .include('api')
  .into(router);
module.exports = router;

/线路/api/player.js

module.exports = function (router) {
  router.use('/player', router);
  router.get('/getInfo', function (req, res, next) {
    res.error = false;
    res.data = {};
    res.message = "Player getInfo API Call - IN DEVELOPMENT";
    next();
  });
};

/线路/api/profile.js

module.exports = function (router) {
  router.use('/profile', router);
  router.get('/getInfo', function (req, res, next) {
    res.error = false;
    res.data = {};
    res.message = "Profile getInfo API Call - IN DEVELOPMENT";
    next();
  });
}

Consign在模块中加载很好,但是当路径相同时,router.use()方法似乎会覆盖回调(忽略基本路径)。例如,"/player/getInfo"answers"/profile/getInfo"都作为调用,但都响应"/profile/getInfo"数据。

顺便说一句——如果你想知道,如果它是相关的,我有一个名为"formatResponse"的中间件,它将以相同的方式获取数据并格式化所有调用,这就是为什么我有一个"next()"而不是从函数本身响应。代码也在下面。

/中间件/formateResponse.js

module.exports = function(req, res, next) {
  res.json({
    error: res.error,
    data: res.data,
    message: res.message
  });
}

你现在做的方式,没有作用域。你把路由器挂载到'/profile'上,然后在'/getInfo'路径上添加一个get语句,实际上并没有像你想象的那样改变作用域。它们都存储在'/getInfo'上以匹配,最后一个获胜(无论前缀如何)。我打赌导航到http://your-server/getInfo也可以)。

你要么需要为每个模块使用不同的路由器(然后在你想要的路径根上挂载那个路由器),要么在其余的路由中更明确(例如调用router.get('/profile/getInfo', ...)