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