我一直在 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/