获取 post 操作的请求正文

Get request body for post operation

我使用 http 模块,我需要获取 req.body 目前我尝试了以下但没有成功。

http.createServer(function (req, res) {

console.log(req.body);

这个return undfiend,知道为什么吗? 我通过邮递员发送一些短文本...

req.body 是一个 Express 特性,据我所知...您可以使用 HTTP 模块像这样检索请求正文:

var http = require("http"),
server = http.createServer(function(req, res){
  var dataChunks = [],
      dataRaw,
      data;

  req.on("data", function(chunk){
    dataChunks.push(chunk);
  });

  req.on("end", function(){
    dataRaw = Buffer.concat(dataChunks);
    data = dataRaw.toString();

    // Here you can use `data`
    res.end(data);
  });
});

server.listen(80)

这是一个非常简单的没有任何框架的方法(不是快速方式)。

var http = require('http');
var querystring = require('querystring');

function processPost(request, response, callback) {
    var queryData = "";
    if(typeof callback !== 'function') return null;

    if(request.method == 'POST') {
        request.on('data', function(data) {
            queryData += data;
            if(queryData.length > 1e6) {
                queryData = "";
                response.writeHead(413, {'Content-Type': 'text/plain'}).end();
                request.connection.destroy();
            }
        });

        request.on('end', function() {
            request.post = querystring.parse(queryData);
            callback();
        });

    } else {
        response.writeHead(405, {'Content-Type': 'text/plain'});
        response.end();
    }
}

用法示例:

http.createServer(function(request, response) {
    if(request.method == 'POST') {
        processPost(request, response, function() {
            console.log(request.post);
            // Use request.post here

            response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
            response.end();
        });
    } else {
        response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
        response.end();
    }

}).listen(8000);

表达框架

在可用于内容类型的 3 个选项的 Postman 中 select "X-www-form-urlencoded"。

app.use(bodyParser.urlencoded())

有:

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

https://github.com/expressjs/body-parser

'body-parser' 中间件只处理 JSON 和 urlencoded 数据,不处理 multipart