使用nodejs,express,body-parser从GET请求中解析主体?

时间:2016-04-05 11:31:00

标签: node.js express body-parser

是否可以使用body检索express内容?

我从尝试body-parser开始,但这似乎与GET无关。有没有可行的模块?

var express = require('express'),
  bodyParser = require('body-parser'),
  PORT = process.env.PORT || 4101,
  app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.route('/')
  .get(function(req, res) {
    respond(req, res, 'GET body contents:\n');
  })
  .post(function(req, res) {
    respond(req, res, 'POST body contents:\n');
  });

app.listen(PORT, function(err) {
  if (err) {
    console.log('err on startup ' + err);
    return;
  }
  console.log('Server listening on port ' + PORT);
});

/*
 * Send a response back to client
 */
function respond(req, res, msg){
  res.setHeader('Content-Type', 'text/plain');
  res.write(msg);
  res.end(JSON.stringify(req.body, null, 2));
}

这是来自GET

的回复
GET body contents:
{}

来自POST

POST body contents:
{
    "gggg": ""
}

1 个答案:

答案 0 :(得分:3)

GET请求没有正文,他们有查询字符串。要在expressJS中访问查询字符串,您应该使用req.query对象。

res.end(JSON.stringify(req.query, null, 2));
相关问题