HTTP GET and POST functions for REST APIs in Node.js

On getting the GET request from the client, the server responds, by revealing some information about itself, and metadata about the data asked by the client.

The response from REST API which is in the form of URL can be obtained by implementing an http get method.

The response are mainly in the form of JSON(JavaScript Object Notation).

Let see how we can handle responses through Node.js


var getapi = require('./getapi.js');
var postapi = require('./postapi.js');


Now let us see the code for individual functions for GET and POST.


var https = require('https');

function httpGet(){
var options = {
 host: 'your api url',
 port: 443,
 path: '/api/xyz?q=123',
 headers: {
 'Authorization': 'Basic ' + new Buffer("username" + ':' + "password").toString('base64')

request = https.get(options, function(res){
 var body = "";
 res.on('data', function(data) {
 body += data;
 res.on('end', function() {
 Response = JSON.parse(body);
module.exports.httpGet = httpGet;


var https = require('https');
function httpPost(){
var options = {
hostname:'your api url',
<div>headers: {</div>
<div>'Authorization':'Basic '+newBuffer("username"+':'+"password").toString('base64'),</div>
<div>var req = https.request(options, function(res) {</div>
<div>res.on('data', function (body) {</div>
<div>console.log('Body: '+body);</div>
<div>req.on('error', function(e) {</div>
<div>console.log('problem with request: '+e.message);</div>
<div>var postdata = "blah blah"</div>
<div>module.exports.httpPost = httpPost;</div>
Check Similar Posts below: