javascript - 'res.location(path)' 什么都不做? (表达)

标签 javascript node.js express handlebars.js httprequest

我一直在 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 ;找不到原因。我发现唯一可能是问题的是浏览器:

After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the Location header, without any validation.

Browsers take the responsibility of deriving the intended URL from the current URL or the referring URL, and the URL specified in the Location header; and redirect the user accordingly.

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

最佳答案

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

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

The Location response header indicates the URL to redirect a page to. It only provides a meaning when served with a 3xx (redirection) or 201 (created) status response.

这会起作用:

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

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

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

关于javascript - 'res.location(path)' 什么都不做? (表达),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50242524/

相关文章:

javascript - Mongoose.find() 参数化没有找到任何东西

angular - 部署/运行: local Express web-server and local client-side angular app that sends ajax requests to this local web-server

JavaScript - 需要加载外部 JS 文件的函数

javascript - 电子邮件未从 heroku Nodejs 应用程序发送(本地工作正常)

javascript - 带有 csrf 的 Braintree webhooks 无法正常工作

node.js - 为什么 sequelize.sync() 总是返回空模型?

node.js - Passport.js 异步与同步反序列化

javascript - 将 JSON 文件加载到 highcharts 中以绘制折线图

javascript - 模态/灯箱打开时如何停止背景滚动体

javascript - 将退出键绑定(bind)到实例?