0

When I do this:

app.post('/account', function(req, res){

    // attempt to validate input and insert user into db
    signUpUser(req.body, function(success){

        if(success){

            // validation and sign up process successful - send to account page
            res.redirect(302, '/account');

        }else{

            // validation or something else failed - redirect to register page 
            // and ask them to try again
            res.redirect(422, '/register');

        }
    };
})

the 302 redirect works just fine, but the 422 redirect sends the user to a page which just reads


422 node response page


How do I stop it doing this? I don't want to display a page that requires the user to click on the link to where it's going, I want it just to go there. I can use a 302 code response instead, but 422 is a more accurate description of what's going on.

Any ideas? Thanks a lot

Joshua
  • 6,320
  • 6
  • 45
  • 62

2 Answers2

3

Its status code beginning with 3 what makes the browser redirect (wikipedia), so naturally you can't have both HTTP-redirection and 422 status code. You have some choices here:

  1. Return 3xx status
  2. Return 422 status and make no redirection
  3. Return any status and use javascript or meta tag to perform redirection

I'd recommend option 2:

  1. If you're building API you don't want any HTTP-redirection just info about what went wrong
  2. If you're building web application it's common practice to redirect upon success and leave form with errors filled when something went wrong (sorry for no source on that, maybe someone can help?)

Method called redirect is just a convenience for setting status 302 (although you can override it as in your example) and Location header. It should be disallowed to use it with status other than 3xx to avoid confusion such as yours.

Community
  • 1
  • 1
joozek
  • 2,143
  • 2
  • 21
  • 32
1

422 might be more appropriate for an API interface, but if you want an end user to end up at the right place you should use 302.

Daniel
  • 38,041
  • 11
  • 92
  • 73