简体   繁体   中英

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.

对于GET请求,请使用req.query.statusreq.query['status']

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM