max
max

Reputation: 617

Express.js one function to handle GET and POST

Is it better to have a separate function to handle GET and POST requests for the same API endpoint or combine them into one function that discriminates based on the existence of req.body or req.params?

i.e.

app.get('/api/profilepic',  api.get_profilepic);
app.post('/api/profilepic',  api.change_profilepic);

or:

app.get('/api/profilepic',  api.profilepic);
app.post('/api/profilepic',  api.profilepic);

If the latter, does Express.js provide a helper function to determine the request type? My approach so far to determine if req is POST requires an underscore:

if (_.size(req.body) == 0)

Upvotes: 5

Views: 8671

Answers (2)

Marrouchi
Marrouchi

Reputation: 281

There is no general rule, the best approach depends on the case you are working on. I think if you want an api endpoint that accept POST and GET requests combined, you should use express function all() like this:

app.all('/api/profilepic',  api.get_profilepic);

You should use seperate endpoints for POST and GET when the handler function is not the same.

For more details see: http://expressjs.com/en/guide/routing.html

Upvotes: 22

Brett
Brett

Reputation: 4269

Best practice is to separate concerns; therefore, you should have separate functions to handle each HTTP verb. This makes the code easier to maintain.

Upvotes: 8

Related Questions