Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 948
user176855 Avatar asked Apr 03 '11 06:04

user176855


People also ask

How do you write a post method in node JS?

Example code: var request = require('request') var options = { method: 'post', body: postData, // Javascript object json: true, // Use,If you are sending JSON data url: url, headers: { // Specify headers, If any } } request(options, function (err, res, body) { if (err) { console. log('Error :', err) return } console.

How do I process a form data in node JS?

To get started with forms, we will first install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware. var express = require('express'); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var app = express(); app.


1 Answers

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

like image 193
yojimbo87 Avatar answered Oct 01 '22 19:10

yojimbo87