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

main_app.js


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

getapi.httpGet();
postapi.httpPost();

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

getapi.js

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;

postapi.js

var https = require('https');
function httpPost(){
var options = {
hostname:'your api url',
port:443,
path:'/api/abc?q=123',</pre>
<div>method:'POST',</div>
<div>headers: {</div>
<div>'Authorization':'Basic '+newBuffer("username"+':'+"password").toString('base64'),</div>
<div>'Content-Type':'application/json',</div>
<div>}</div>
<div>};</div>
<div>var req = https.request(options, function(res) {</div>
<div>res.setEncoding('utf8');</div>
<div>res.on('data', function (body) {</div>
<div>console.log('Body: '+body);</div>
<div>});</div>
<div>});</div>
<div>req.on('error', function(e) {</div>
<div>console.log('problem with request: '+e.message);</div>
<div>});</div>
<pre></pre>
<div>var postdata = "blah blah"</div>
<pre></pre>
<div>req.write(postdata);</div>
<div>req.end();</div>
<div>}</div>
<pre></pre>
<div>module.exports.httpPost = httpPost;</div>
<div>
Check Similar Posts below:
Advertisement