'res.location(path)' does not do anything? (Express)

亡梦爱人 提交于 2020-01-25 05:49:06

问题


I have been searching around for answers on Stack Overflow; non have worked... Why does res.location(path) not work? My Location-header does not change. Normal rendering works fine.

I could add, that in the final code, I want to render the page. So, I want to replace res.end() with res.render('app', {...}) and use handlebars.js for rendering.

Code that does not work as expected:

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

I have been reading the documentation; could not find the reason. The only thing I found that could be the problem, is the browser:

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.

  • I have tried this with the latest Node.js compatible with Firebase SDK 2018 (server)
  • I have tried this in Google Chrome and IE Edge (client)

回答1:


res.location doesn't set the response status code to 3xx or 201. It only set the Location header.

You can use res.redirect instead which set the status code to 302 and will make the browser change the 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.

This will work:

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

or

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

You can check res.location & res.redirect code to see the differences between them.



来源:https://stackoverflow.com/questions/50242524/res-locationpath-does-not-do-anything-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!