Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

app.get and app.post get value in node.js

I'm using the app.get and app.post functions in Express on Node.js.

I have examples like this:

app.post('/status', function(req, res) {
  if (~packages.STATUSES.indexOf(req.body['status'])) {
    res.status(req.body.status, req.body.message);
    res.jsonp(new packages.Success('status updated'));
  } else {
    res.jsonp(new packages.Error('invalid status'));
  }
});

This will work if I post the data to the sever, and I noticed that it gets the value by

req.body['status'];

What if I use GET and pass the value here? What should I do to get the 'status'?

app.get('/status', function(req, res) {
// how can I get status... var status = ??
  if (~packages.STATUSES.indexOf(status) { //got value
    res.status(req.body.status, req.body.message);
    res.jsonp(new packages.Success('status updated'));
  } else {
    res.jsonp(new packages.Error('invalid status'));
  }
});

Sorry if it sounds dumb but I did some research and couldn't find any examples online. Thanks for your help.

like image 600
jackhao Avatar asked Feb 14 '26 21:02

jackhao


1 Answers

I would strongly suggest to use

req.param('status') //

it looks up req.body/req.query as well as req.params, so with this you can map all three below routes to the same method

app.get('/status',statusHanlder);
app.post('/status', statusHanlder);
app.get('/status/:status', statusHanlder)

var statusHanlder = function(req, res){
  var status = req.param('status')
}
like image 122
Sriharsha Avatar answered Feb 16 '26 10:02

Sriharsha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!