Posting JSON data with Node.js

More than likely your Node.js application is acting like some sort of web service. Every once in a while your web service needs to communicate with another one. In this tutorial I’m going to demonstrate how to invoke an HTTP request using Node.js and post some JSON data to it.

My assumption for this article is that you’ve already got a Node.js application up and running, so I’m going to skip most of the boilerplate code and get right to the important stuff. The first thing we’ll need is some data to post, which you’ve probably already got, but here’s mine.

var user = {
  username: ‘The Reddest’,
  email: [email protected],
  firstName: ‘Brandon’,
  lastName: ‘Cannaday’
};

You can post data in several ways, but the most common and what we’re going to use is string data. Fortunately it’s super simple to convert an object into a string using the built-in JSON class.

var user = {
  username: ‘The Reddest’,
  email: [email protected],
  firstName: ‘Brandon’,
  lastName: ‘Cannaday’
};

var userString = JSON.stringify(user);

Now we need to tell the remote server what kind of data we’re sending, in the form of headers.

var user = {
  username: ‘The Reddest’,
  email: [email protected],
  firstName: ‘Brandon’,
  lastName: ‘Cannaday’
};

var userString = JSON.stringify(user);

var headers = {
  ‘Content-Type’: ‘application/json’,
  ‘Content-Length’: userString.length
};

The “Content-Type” header tells the remote server we’re going to be sending a JSON string. The “Content-Length” is just the number of characters we’re sending. If you’re sending files, this field will be how large the file is, in bytes.

Next up we need to specify what server we want to talk to and how we’re going to do it. This is done using a simple options object. This object will be supplied to Node.js when we make the actual request.

var user = {
  username: ‘The Reddest’,
  email: [email protected],
  firstName: ‘Brandon’,
  lastName: ‘Cannaday’
};

var userString = JSON.stringify(user);

var headers = {
  ‘Content-Type’: ‘application/json’,
  ‘Content-Length’: userString.length
};

var options = {
  host: ‘myServer.example.com’,
  port: 80,
  path: ‘/user/TheReddest’,
  method: ‘POST’,
  headers: headers
};

In my example I’m going to post data to myServer.example.com:80/User/TheReddest. Notice that there is no leading ‘http://’ in front of the host – DO NOT add a leading ‘http://’ to the host.

Now it’s time to make the actual request. Fortunately Node.js makes this pretty easy.

var http = require(‘http’);

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {

});

So far, we haven’t actually done anything. We still need to write our data to the request and read the response. Let’s start with writing our data.

var http = require(‘http’);

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {

});

req.write(userString);
req.end();

At this point, the remote server will received your posted data. All that’s left is to read the response. This is done inside the callback that’s supplied to the http.request function.

var http = require(‘http’);

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {
  res.setEncoding(‘utf-8’);

  var responseString = ;

  res.on(‘data’, function(data) {
    responseString += data;
  });

  res.on(‘end’, function() {
    var resultObject = JSON.parse(responseString);
  });
});

req.write(userString);
req.end();

The response that comes back from the remote server can appear in multiple chunks. This means the ‘data’ callback may be invoked multiple times. The responses do come back in order, so all we have to do is append all the responses together into a single string. The ‘end’ callback will be invoked when everything has been received. The remote server you’re connecting to may or may not return JSON, but in my example it does, so I simply use JSON.parse to convert it into a usable object.

The last thing you’ll probably want to do is handle errors. This is done by simply hooking the ‘error’ event on the request object.

var http = require(‘http’);

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {
  res.setEncoding(‘utf-8’);

  var responseString = ;

  res.on(‘data’, function(data) {
    responseString += data;
  });

  res.on(‘end’, function() {
    var resultObject = JSON.parse(responseString);
  });
});

req.on(‘error’, function(e) {
  // TODO: handle error.
});

req.write(userString);
req.end();

Just for good measure, here’s all the code in one piece:

var http = require(‘http’);

var user = {
  username: ‘The Reddest’,
  email: [email protected],
  firstName: ‘Brandon’,
  lastName: ‘Cannaday’
};

var userString = JSON.stringify(user);

var headers = {
  ‘Content-Type’: ‘application/json’,
  ‘Content-Length’: userString.length
};

var options = {
  host: ‘myServer.example.com’,
  port: 80,
  path: ‘/user/TheReddest’,
  method: ‘POST’,
  headers: headers
};

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {
  res.setEncoding(‘utf-8’);

  var responseString = ;

  res.on(‘data’, function(data) {
    responseString += data;
  });

  res.on(‘end’, function() {
    var resultObject = JSON.parse(responseString);
  });
});

req.on(‘error’, function(e) {
  // TODO: handle error.
});

req.write(userString);
req.end();

And there you have it. This tutorial demonstrates how to POST JSON data to a remote server using Node.js. If you have any questions or comments feel free to leave them below.

Leave a Reply

Your email address will not be published. Required fields are marked *