Reputation: 1796
it is possible to modify node js requested url?? browser sending me request like this
http://localhost/user/add
when its comes to server i want to add api in my current request i mean like below request.
http://localhost/api/user/add
for this i have written one middle ware but look like its not working.
app.use('*', function(req, res, next) {
if (req.baseUrl.indexOf('api') == -1) {
req.baseUrl = '/api' + req.baseUrl;
console.log('req.baseUrl');
console.log(req.baseUrl);
}
next();
});
above code not working please tell me what's i am doing wrong.
Upvotes: 1
Views: 3036
Reputation: 1914
You need to re-fire router to handle updated urls:
app.use('*', function(req, res, next) {
if (req.baseUrl.indexOf('api') == -1) {
req.url = '/api' + req.url;
req.originalUrl = '/api' + req.originalUrl; //update all 3 just to be
safe.
req.baseUrl = '/api' + req.baseUrl;
console.log('req.baseUrl');
console.log(req.baseUrl);
app.handle(req, res); //re-fire router to handle updated urls
}
next();
});
Upvotes: 1
Reputation: 852
Please try assign the req.url and req.originalUrl. They are key point for rewrite request. https://expressjs.com/en/api.html
This property is much like req.url; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes. For example, the “mounting” feature of app.use() will rewrite req.url to strip the mount point.
On the other hand, express-urlrewrite is an open-sourced library for express url rewrite. You could be inspired from it.
Upvotes: 1