Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expressjs one function to handle GET and POST

Is it is 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?

ie.

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 expressjs provide a helper function to determine the request type? My approach so far to determine if req is POST requires underscore:

if (_.size(req.body) == 0)
like image 752
max Avatar asked Nov 28 '22 21:11

max


2 Answers

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

like image 131
Marrouchi Avatar answered Dec 05 '22 13:12

Marrouchi


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

like image 43
Brett Avatar answered Dec 05 '22 13:12

Brett