【问题标题】:'res.location(path)' does not do anything? (Express)'res.location(path)' 什么都不做? (表示)
【发布时间】:2018-10-18 22:21:20
【问题描述】:

我一直在 Stack Overflow 上寻找答案;没有工作...为什么res.location(path) 不起作用?我的 Location-header 没有改变。正常渲染效果很好。

我可以添加,在最终代码中,我想呈现页面。所以,我想用res.render('app', {...}) 替换res.end() 并使用handlebars.js 进行渲染。

无法按预期工作的代码

app.get('/sub-link/:wildcard', (req, res) => {
    res.location('/new-header');
    res.end();
});

我一直在看documentation;找不到原因。我发现唯一可能是浏览器的问题:

在对 URL 进行编码后,如果尚未编码,Express 会通过 在 Location 标头中指定浏览器的 URL,没有任何 验证。

浏览器负责从 当前 URL 或引用 URL,以及在中指定的 URL 位置标题;并相应地重定向用户。

  • 我已经使用与 Firebase SDK 2018 兼容的最新 Node.js 进行了尝试(服务器)
  • 我已在 Google Chrome 和 IE Edge 中尝试过此操作(客户端)

【问题讨论】:

    标签: javascript node.js express handlebars.js httprequest


    【解决方案1】:

    res.location 没有将响应状态码设置为 3xx 或 201。它只设置了 Location 标头。

    您可以使用res.redirect 来代替,它将状态码设置为 302,并使浏览器更改 URL。

    Location 响应标头指示要将页面重定向到的 URL。 只有在使用 3xx(重定向)或 201 时才有意义 (已创建)状态响应。

    这将起作用:

    app.get('/sub-link', (req, res) => {
        res.location('/new-header');
        res.send(302);
    });
    

    app.get('/sub-link', (req, res) => {
        res.redirect('/new-header');
    });
    

    您可以查看res.locationres.redirect 代码以查看它们之间的差异。

    【讨论】:

    • 啊,我明白了。我误解了它的用法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 2019-03-08
    • 2016-12-24
    • 2017-04-18
    • 2011-08-03
    • 2014-05-11
    相关资源
    最近更新 更多