14

I've used this code 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!

1 Answer 1

20

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

Sign up to request clarification or add additional context in comments.

2 Comments

I'm googling and I noticed your answer is from a year ago... is this still accurate? Also, I'm using express, which clearly isn't being used here
The problem here is that the response will not be correctly formatted JSON.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.