修改req.url;t更新url参数(req.query)

Modifying req.url doesn't update the url parameters (req.query)

本文关键字:req url query 参数 修改 更新      更新时间:2023-09-26

由于Google Sitemap在其XML中不允许&。我已经转义了包含两个参数的url(如"/path?a=123&b=hello"),现在变成了/path?a=123%26b=hello,我认为浏览器会自动取消对url的转义。但事实并非如此。而谷歌机器人正在给出错误。

因此,在调用上述路由之前,我在堆栈顶部添加了一个中间件函数。

app.use(function (req, res, next) {
        debug(req.url);
        req.url = unescape(req.url);
        debug(req.url);
        // This works as expected
        next();
});

但当我执行req.query.areq.query.b时(谷歌机器人使用转义URL访问,即/path?a=123%26b=hello),它给出了原始值,即req.query.a gives 123%26b=helloreq.query.b gives undefined,当我检查req.url时,它给出的是正确的未转义URL。

你有什么建议?

更新:

我能想到的一个快速解决方案是(我还没有尝试过,但我认为它会起作用)

// After unescaping req.url
// test.com/path?a=123&b=hello
var query = req.url.split('?')[1].split('&');
var a = query[0].split('=')[1];
var b = query[1].split('=')[1];
// It looks very dirty

在XML中,应该将&转义为&:

/path?a=123&b=hello

%26用于您已经发现的值内的&符号。

尝试HTML5 History API,它会起作用:

History.pushState()