Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node: Basic JSON request

Node: Basic JSON request

Problem

I'm a complete beginner in Node.js and I wanted to consult something I could not figure out.

Even though I've researched extensively I could not find any method to receive JSON Request without using a plugin. I will be using it to program a mobile application API. But even though I've incluede parameter request I cannot reach the content by using request.body, or request.data. The request I'm trying to make is;

{
    "id":"123"
}

And my failing code is;

var http = require('http');

function onRequest(request, response){
    console.log("Request: "+request.data+"\n");
    response.writeHead(200, {"Content-Type":"text/plain"});
    response.write("Hello, World");
    response.end();
}

http.createServer(onRequest).listen(8888);
Problem courtesy of: Ali

Solution

The problem here is that you're not listening to the request events to let you know that you have data, and then parsing the data. You're assuming that request has request.data.

It should be:

var http = require('http');

function onRequest(request, response){
  var data = '';
  request.setEncoding('utf8');

  // Request received data.
  request.on('data', function(chunk) {
    data += chunk;
  });

  // The end of the request was reached. Handle the data now.
  request.on('end', function() {
    console.log("Request: "+data+"\n");
    response.writeHead(200, {"Content-Type":"text/plain"});
    response.write("Hello, World");
    response.end();
  });
}

http.createServer(onRequest).listen(8888);

See this for the documentation for the methods that request contains.

Solution courtesy of: Sly

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node: Basic JSON request

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×