简体   繁体   中英

Get the request.body in NodeJs

I have this basic server:

var http = require("http");
var url = require("url");

var routing = require("./RoutingPath");

function start() {  
    function onRequest(request, response) {

        var path = url.parse(request.url).pathname;
        var query = url.parse(request.url,true).query;

        routing.Route(path.toLowerCase(), query, function(recordset){

            response.writeHead(200, {"Content-Type": "application/json"});

            if (recordset != null)
            {
                console.log(JSON.stringify(recordset, null, 4));                
                response.write(JSON.stringify(recordset, null, 4));
            }

            response.end();
            console.log();
        });
  }

  http.createServer(onRequest).listen(8888);
  console.log("Server has started!");

}

I use "HttpRequester" to post a request, and add attachment within in (small file) or use the content textbox to send data in it. In my server I get the request but no access to it's body. I tried:

console.log(request.body);

But it's undefined.

I tried to print all request to look for my data, but it's too long and I can't see all the request.

I tried other request because I thought "HttpRequester" may not send me the right request by a friend who sent it to me from the client.

How can I access the body of the request?

If you need to use the default http module you need to read the request body from the data stream:

if (request.method == 'POST') {
    request.on('data', function(chunk) {
      console.log("Received body data:");
      console.log(chunk.toString());
    });
}

I would recommend you to have a look at expressjs , it already features routing and has various body parser's for files/json etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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