What are the steps to send a https request in node js to a rest service? I have an api exposed like https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school
How to pass the request and what are the options I need to give for this API like host, port, path and method?
The easiest way is to use the request module.
request('https://example.com/url?a=b', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
just use the core http module with the http.request function. Example for a POST
request (GET
would be similar):
var http = require('http');
var options = {
host: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
You can use superagent and node's url module do build up a request like so:
var request = require('superagent');
var url = require('url');
var urlObj = {
protocol: 'https',
host: '133-70-97-54-43.sample.com',
pathname: '/feedSample/Query_Status_View/Query_Status/Output1'
};
request
.get(url.format(urlObj))
.query({'STATUS': 'Joined school'})
.end(function(res) {
if (res.ok) {
console.log(res.body);
}
});
Using the request module solved the issue.
// Include the request library for Node.js
var request = require('request');
// Basic Authentication credentials
var username = "vinod";
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(
{
url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
console.log(body); } );