英文:
Same route, different query but different middlewares
问题
I understand your request. Here's the translated code portion without the parts you mentioned not to translate:
我正在处理一个具有以下路由的 API(全部都是 POST 请求)
`/friends?d=onlineFriends`
`/friends?d=offlineFriends`
等等…
以及它是如何处理的:
`server.js`
```js
app.post("/friends", (req, res, next) => {
let d = req.query.d;
let path = "./funcs/" + d + ".js";
return require(path)(req, res, next);
})
./funcs/onlineFriends.js
module.exports = (req, res, next) => {
return res.sendStatus(200);
}
但问题是,我想为每个函数使用不同的中间件。使用上面的代码,如果我想使用中间件,它将应用于所有函数,因为你必须将它放在 app.post
部分。
我尝试过以下方法:
module.exports = (req, res, next) => {
middleware(req, res, next);
return res.sendStatus(200);
}
但当然会导致 Cannot set headers after they are sent to the client
错误。
我知道你可能会问:“为什么不使用像 /friends/online 这样的路由?”但我真的无法更改客户端,我必须这样做。
Please note that I've translated the code portion while excluding the parts you specified not to translate.
<details>
<summary>英文:</summary>
I'm working on an API that has routes like this (all POST requests)
`/friends?d=onlineFriends`
`/friends?d=offlineFriends`
and on...
and this is how it's handled:
`server.js`
```js
app.post("/friends", (req, res, next) => {
let d = req.query.d
let path "./funcs/" + d + ".js"
return require(path)(req, res, next)
})
./funcs/onlineFriends.js
module.exports = (req, res, next) => {
return res.sendStatus(200)
}
But the thing is, I want to use different middlewares per func, with the code above if I wanted to use a middleware it would apply to all funcs because you'd have to put it in app.post part.
I've tried following:
module.exports = (req, res, next) => {
middleware(req, res, next)
return res.sendStatus(200)
}
but of course it results in Cannot set headers after they are sent to the client
.
I know you might ask "Why not use a router like /friends/online", I really can't change the client and this is how I must do it.
答案1
得分: 1
如果您有中间件 a
、b
和 c
,您可以动态选择它们的组合并使用它们来处理请求:
app.post("/friends", function(req, res, next) {
var middleware;
switch (req.query.d) {
case "a": middleware = [a, c]; break;
case "b": middleware = [b]; break;
default: return next();
}
express.Router().use(middleware)(req, res, next);
});
英文:
If you have middlewares a
, b
and c
, you can dynamically choose a combination of them and use that to handle the request:
app.post("/friends", function(req, res, next) {
var middleware;
switch (req.query.d) {
case "a": middleware = [a, c]; break;
case "b": middleware = [b]; break;
default: return next();
}
express.Router().use(middleware)(req, res, next);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论