Redirect POST to POST using Express JS routes

2019-01-20 18:52发布

问题:

So I have a landing page ('/'). On this page is a login form for a username and password with a submit button. I have the app.get that loads the page and an app.post to receive the parameters of the form. However, my intention is to have an app.post('/login', function (req, res){ //logic}); There is no /login route or page to load, this would simply house the logic for the login itself (validation of the username, etc.) Is there an easy way to get the post from '/' to redirect into the post for /login without it trying to load the /login page, which does not exist?

回答1:

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.