Redirect POST to POST using Express JS routes

爱⌒轻易说出口 提交于 2019-11-28 14:39:23

I'm not sure if I understand your question correctly. As I understand you want your POST request to / get redirected to POST requests to /login which can be tricky.

Usually you do redirects by sending either 301 Moved Permanently or 302 Found HTTP status code. Both of them usually work in practice as if it was 303 See Other and a GET request is made. See List of HTTP status codes on Wikipedia:

This is an example of industry practice contradicting the standard. The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302 with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to distinguish between the two behaviours. However, some Web applications and frameworks use the 302 status code as if it were the 303.

There is a 307 Temporary Redirect (since HTTP/1.1) created to address this issue that is not allowed to change the HTTP method - so a redirect from POST should still be POST - see Wikipedia:

In this case, the request should be repeated with another URI; however, future requests should still use the original URI. In contrast to how 302 was historically implemented, the request method is not allowed to be changed when reissuing the original request. For example, a POST request should be repeated using another POST request.

As far as I know browsers should warn users before following such redirects. I don't know how that works in practice. I wouldn't rely on that since it can be annoying to users at best or even not work at all.

My suggestion would be to either change this:

app.post('/login', function (req, res) {
  // logic
}); 

to this:

function loginHandler(req, res) {
  // logic
}
app.post('/login', loginHandler); 
app.post('/', loginHandler); 

or something like this, using regular expressions:

app.post(/^\/(?:login)?$/, function (req, res) {
  // logic
}); 

That way instead of a redirect the same handler will be used for both of those routes. It would be both faster and more robust because that way you don't rely on the redirect working as you want - there is no redirect at all.

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