获取发布操作的请求正文

时间:2015-06-21 18:36:05

标签: javascript node.js node-http-proxy

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

http.createServer(function (req, res) {

console.log(req.body);
这回归不知道,任何想法为什么? 我通过邮递员发送一些简短的文字......

2 个答案:

答案 0 :(得分:2)

这里非常简单,没有任何框架(不明确的方式)。

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

表达框架

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

app.use(bodyParser.urlencoded())

使用:

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

请参阅https://github.com/expressjs/body-parser

'身体解析器'中间件只处理JSON和urlencoded数据,而不是多部分

答案 1 :(得分:0)

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)
相关问题