开发者

How to do a simple read POST data in Node JS?

I've used this c开发者_JAVA百科ode to read the querystring ?name=Jeremy ...can anyone tell me how to do this with post data? also with json?

var http = require('http'), url = require('url');
http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type":"text/plain"});
    var urlObj = url.parse(request.url, true);
    response.write("Hello " + urlObj.query["name"] + "!\n");
}).listen(8000);

thanks!


You have to handle data and end events of http.ServerRequest object. Example:

var util = require("util"),
    http = require('http'), 
     url = require('url'),
      qs = require('querystring');

...

// this is inside path which handles your HTTP POST method request
if(request.method === "POST") {
    var data = "";

    request.on("data", function(chunk) {
        data += chunk;
    });

    request.on("end", function() {
        util.log("raw: " + data);

        var json = qs.parse(data);

        util.log("json: " + json);
    });
}

Here is an article on this topic with example (with too old version of node.js so it might not work, but the principle is the same).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜