0

我正在尝试在 Express 中实现一些应该为所有路由调用的中间件。这个中间件应该改变请求对象。

我已经尝试了几件事,但似乎一直遇到同样的问题。离开中间件后,看起来请求对象就变回了它的原始状态。

目前我的代码类似于(我用一个简约的例子简化了它):

路由.js:

const express = require('express');
const router = express.Router();
router.get('/getMe', (req, res) => {
  // return the desired data.
  // I expect req.params.myString to exist here but it does not.
});
module.exports = router;

index.js:

const express = require('express');
const router = express.Router();
router.use('/', require('./route'));
module.exports = router;

应用程序.js:

const express = require('express');
const app = express();
const routes = require('./index');

app.use((req, res, next) => {
  // Adding req.params.myString to the request object.
  if (req.params.myString === undefined) req.params.myString = 'hello world';
  next();
});

app.use('/api', routes);

如您所见,我省略了一些代码以使其更具可读性。这是获取响应并设置服务器的代码。

同样,我期待 req.params.myString 在端点中可用。有谁看到我做错了什么?

4

2 回答 2

2

在快递文档(http://expressjs.com/en/api.html#req.params)中它说:

如果您需要更改 req.params 中的键,请使用 app.param 处理程序。更改仅适用于已在路由路径中定义的参数。

所以你需要检查 app.param 处理程序。

http://expressjs.com/en/4x/api.html#app.param

于 2019-10-22T10:52:11.440 回答
1

你应该app.set("myString", "hello World")在你的 app.js 中,然后你可以通过使用访问你的 route.js/index.js 脚本中的字段req.app.get("myString")。或者这也应该起作用,设置它app.myString = "Hello world"并像访问它一样req.app.myString

于 2019-10-22T14:17:02.630 回答