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)
rgettman
  • 176,041
  • 30
  • 275
  • 357
max
  • 617
  • 8
  • 20
  • 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). – robertklep Jan 08 '14 at 17:46
  • 7
    There's also `app.all()` to handle both (and more) – adeneo Jan 08 '14 at 17:57

2 Answers2

21

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

Marrouchi
  • 271
  • 2
  • 4
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.

Brett
  • 4,268
  • 1
  • 13
  • 28