jackhao
jackhao

Reputation: 3817

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.

Upvotes: 3

Views: 7473

Answers (2)

Sriharsha
Sriharsha

Reputation: 2443

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')
}

Upvotes: 3

tymeJV
tymeJV

Reputation: 104775

Use req.query.status or req.query['status'] for GET requests.

Upvotes: 2

Related Questions