Reputation: 1970
I am trying to rewrite any query parameter of '?locale=en' to '/' and i don't want to redirect in app.js i wrote before the router and it didn't work, the browser still has the same link.
var locale = req.query.locale;
var old_url = req.url;
if(locale=='en'){
req.url = req.protocol + '://' + req.get('host') + req.originalUrl.replace("/?locale=" +
locale,"");
}
console.log('foo: ' + old_url + ' -> ' + req.url);
next();
Upvotes: 0
Views: 175
Reputation: 3924
const express = require("express");
const app = express();
app.use((req, res, next) => {
let locale = req.query.locale;
let old_url = req.url;
if (locale == 'en') {
req.url = `${req.protocol}://${req.get("host")}${req.originalUrl.replace(`?locale=${locale}`, "")}`
}
console.log('foo: ' + old_url + ' -> ' + req.url);
next();
});
app.use((req, res, next) => {
res.end(req.url);
});
app.listen(8080);
Just remove the trailing/leading slash in the replace
foo: /my/path?locale=en -> http://127.0.0.1:8080/my/path
BUT: you are set with this code the req.url
property to the whole path (incl. fqdn) and not only the url/path as its original purpose: https://nodejs.org/api/http.html#http_message_url
Upvotes: 1