How to post a JSON request in Node.js

Hi guys, today I will post a code snippet to send a post request to the server in Node.js. This could be useful when testing integration between two different websites. For example, when you need to create/update something on a backoffice and you need to check the details on a front-end website.

  • First you need to install this request module with npm:
npm install sync-request

 

  • After you just need to create the js file with the code:
'use strict';

var request = require('sync-request');

var APIMounts = function() {

 var client = {
 id: '123456',
 name: 'Test Client',
 description: 'This client is used for automation',
 age: '20 years',
 city: 'London',
 interests: [{ 'music': 'Rock' }]};

 var details = {
 method: 'POST',
 url: 'http://google.com/rest/client',
 headers: {
 'Content-Type': 'application/json'
 },
 body: JSON.stringify(client)
 };

 function callback(error, response, body) {
 if (!error && response.statusCode === 200) {
 return JSON.parse(body);
 }
 }
 request(details, callback);
};

module.exports = APIMounts;

 

  • client is a variable that will need be formatted
  • interests contains an array of strings with key:value
  • url is the host
  • body is the client variable JSON formatted

 

Resources:

http://blog.modulus.io/node.js-tutorial-how-to-use-request-module

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: