我正在尝试在 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 在端点中可用。有谁看到我做错了什么?