繁体   English   中英

获取请求主体以进行后期操作

[英]Get request body for post operation

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

http.createServer(function (req, res) {

console.log(req.body);

这种回报无敌,为什么? 我通过邮递员发送了一些短消息...

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

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个选项的邮递员中,选择“ X-www-form-urlencoded”。

app.use(bodyParser.urlencoded())

带有:

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

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

“ body-parser”中间件仅处理JSON和urlencoded数据,而不是多部分

据我所知, 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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