83

I am building a registration form (passport-local as authentication, forms as form helper).

Because the registration only knows GET and POST I would like to do the whole handling in one function.

With other words I am searching after something like:

exports.register = function(req, res){
    if (req.isPost) {
       // do form handling
    }
    res.render('user/registration.html.swig', { form: form.toHTML() });
};

2 Answers 2

155

The answer was quite easy

exports.register = function(req, res) {
    if (req.method == "POST") {
       // do form handling
    }
    res.render('user/registration.html.swig', { form: form.toHTML() });
};

But I searched a long time for this approach in the express guide.

Finally the node documentation has such detailed information: http://nodejs.org/api/http.html#http_http_request_options_callback

Sign up to request clarification or add additional context in comments.

3 Comments

Right. It is pity that the express.js document has missed these things here expressjs.com/api.html#req.params and it doesn't refer the documentation of the NodeJS built-in library, which is really necessary.
Hi, thanks for posting this solution. For me though, to make the logic work as you have listed there, I had to make my IF statement this way : if (req.method != 'GET')
It would be better if you use triple equal character instead of double equal when you compare strings
-7

Now you can use a package in npm => "method-override", which provides a middle-ware layer that overrides the "req.method" property.

Basically your client can send a POST request with a modified "req.method", something like /registration/passportID?_method=PUT.

The

?_method=XXXXX

portion is for the middle-ware to identify that this is an undercover PUT request.

The flow is that the client sends a POST req with data to your server side, and the middle-ware translates the req and run the corresponding "app.put..." route.

I think this is a way of compromise. For more info: method-override

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.