[英]How do I delegate a request to a particular route in nodejs express?
const API_VERSION = {
"authenticate" : "v1",
"users'" : "v1",
"requests" : "v2",
}
I have following routes:我有以下路线:
app.use('/api/v1/authenticate', authenticate);
app.use('/api/v1/users', users);
app.use('/api/v1/requests', requestService);
app.use('/api/v2/requests', requestService_v2);
If a request comes for say api/v1/authenticate
, then it should be re-routed to api/v2/authenticate
.如果请求说
api/v1/authenticate
,那么它应该重新路由到api/v2/authenticate
。
I tried我试过
app.use('/api/v2/*', (req, res, next) => {
const originalUrl = req.originalUrl;
const endPoint = originalUrl.match(/(?<=\/[^\/]*\/[^\/]*\/)[^\/]+(?=\/)/g)[0].toLowerCase();
req.baseUrl = req.originalUrl.replace("v2", API_VERSIONS[endPoint]);
next('route');
});
But this does not work.但这不起作用。
I use app all and pipe the request after modifying the url.我使用 app all 并在修改 url 后通过管道发送请求。 You can also reroute it to a diff.
您也可以将其重新路由到差异。 server eg
服务器例如
API_V1 = '/api/v1'
app.all('/api/v2/*', (req, res)->
url = API_V1 + req.url
req.pipe(request[req.method.toLowerCase()](url, (error)->
res.json({err: error}) if error?
)).pipe(res).on
)
I haven't tried your code but maybe just call next()我没有试过你的代码,但也许只是调用 next()
I did the following我做了以下
app.use('/api/v2/*', (req, res, next) => {
const originalUrl = req.originalUrl;
const endPoint = originalUrl.match(/(?<=\/[^\/]*\/[^\/]*\/)[^\/]+(?=\/)/g)[0].toLowerCase();
const url = req.originalUrl.replace("v2", API_VERSIONS[endPoint]);
res.redirect(307, url);
});
It works, but I'm eager to know if there's any other way to do it.它有效,但我很想知道是否还有其他方法可以做到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.