简体   繁体   English

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

[英]Get request body for post operation

I use the http module and I need to get the req.body currently I try with the following without success . 我使用http模块,目前需要获取req.body,但我尝试以下操作未成功。

http.createServer(function (req, res) {

console.log(req.body);

this return undfiend ,any idea why? 这种回报无敌,为什么? I send via postman some short text... 我通过邮递员发送了一些短消息...

Here's a very simple without any framework (Not express way). 这是一个非常简单的没有任何框架的方法(非表达方式)。

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();
    }
}

Usage example: 用法示例:

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);

express framework 表达框架

In Postman of the 3 options available for content type select "X-www-form-urlencoded". 在可用于内容类型的3个选项的邮递员中,选择“ X-www-form-urlencoded”。

app.use(bodyParser.urlencoded())

With: 带有:

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

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

The 'body-parser' middleware only handles JSON and urlencoded data, not multipart “ body-parser”中间件仅处理JSON和urlencoded数据,而不是多部分

req.body is a Express feature, as far as I know... You can retrieve the request body like this with the HTTP module: 据我所知, 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