crankshaft
crankshaft

Reputation: 2677

node express handling POST and GET as a single request

I would like to handle both POST and GET requests as a single request, such that all of my routings and subsequent functions only need to process a single request, rather than duplicating everything once for GET and again for POST.

So I figure the simplest way of doing this is to convert a POST to a GET early on using middleware, is there any problem with this ?

if(req.method=='POST'){
  req.method = 'GET';
  req.query = req.body;
  delete(req.body);
}

Upvotes: 0

Views: 1242

Answers (3)

Francis Omondi
Francis Omondi

Reputation: 31

You can have the same handler function for the both requests i.e

app.get('/', handlerFunction);
app.post('/', handlerFunction);

Upvotes: 2

code-jaff
code-jaff

Reputation: 9330

Recommended approach is to have the same handler function for both in this case. for eg.

app.get('/path', handler);
app.post('/path', handler);

Upvotes: 0

Mike
Mike

Reputation: 3940

You can have express respond to all POST requests as 302 redirects to the same URL (these are always GET requests).

Here's some sample code:

// Redirect all post requests
app.post('^*$', function(req, res) {

      // Now just issue the same request again, this time as a GET
      res.redirect(302, req.url);

    });
});

Side note: this will work but I wouldn't recommend this as a long term solution. If you decide you do need to handle POST requests differently from GET requests and the maintainability will become a pain. In the long run, you're better off having a clear definition for how to handle POST and GET requests rather than treating them the same.

Upvotes: 1

Related Questions