使用 nodejs、express、body-parser 从 GET 请求中解析 body?

Parse body from GET request using nodejs, express, body-parser?

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

我开始尝试 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": ""
}

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

res.end(JSON.stringify(req.query, null, 2));