我正在编写一个 Express 应用程序,我正在使用 AirBnB eslint configuration 进行检查.该 lint 配置提供了一个 no-params-reassign
检查,它将参数的重新分配和这些参数的成员标记为错误。我个人喜欢这样,但我不确定是否有一种方法可以在不改变函数参数的情况下修改 Express 中的 req
和 res
。
比如我想在一个中间件中重写部分请求:
app.use((req, res, next) => {
req.url = req.url.replace("regex", "replacement");
});
这会引发 lint 错误。我知道我可以通过这样做来消除错误:
app.use((_req, res, next) => {
req = _req;
req.url = req.url.replace("regex", "replacement");
});
...但这似乎是一个有点愚蠢的解决方案。是否有一种方法可以为 Express 中的 future 中间件调用替换 req
和 res
变量,或者是持久更改以实际改变它们的唯一方法?
我知道我可以覆盖 no-params-reassign
规则,但我想看看我是否有可能在不这样做的情况下实现这一目标。谢谢!
最佳答案
Is there a means of replacing the req and res variables for future middleware invocations in Express:
在第一次调用时使用 app
对象作为持久存储,然后在后续调用时检查它
app.use( (req, res, next) => {
app.req = app.req || req;
app.req.url = app.req.url.replace("regex", "replacement");
});
JSON.stringify
和 JSON.parse
可用于避免突变:
app.use( (req, res, next) => {
app.req = app.req || JSON.parse(JSON.stringify(req));
app.req.url = app.req.url.replace("regex", "replacement");
});
引用资料
关于javascript - 修改 res 而不改变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36756947/