Express.js one function to handle GET and POST
Asked Answered
G

2

5

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)
Gourd answered 8/1, 2014 at 17:43 Comment(2)
Judging from your function names, they perform different tasks. So I would keep them separated. FWIW, you can check req.method to see if it contains GET or POST (or some other method, even).Endostosis
There's also app.all() to handle both (and more)Durning
C
8

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

Cotsen answered 8/1, 2014 at 17:54 Comment(0)
H
22

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

Heeltap answered 27/2, 2016 at 10:21 Comment(1)
I tried to use "use" but it didnt work, thaks for "all"Kibe
C
8

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

Cotsen answered 8/1, 2014 at 17:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.