I have a node.js application and I want to call a REST api by using http.request. This is my code:
http = require("http");
const options = {
host: localhost,
port: 8103,
path: "/rest/getUser?userId=12345",
method: "GET"
};
http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
resolve(JSON.parse(chunk));
});
}).end();
The above code works fine, but I don't want to include the request parameter ?userId=12345 in the path. The path should be: /rest/getUser. How do I set the request parameter with http.request?
You can use request package, which has more features, instead of built in http client.
var request = require('request');
var url = 'http://localhost:8103/rest/getUser/';
var paramsObject = { userId:12345 };
request({url:url, qs:paramsObject}, function(err, response, body) {
if(err) { console.log(err); return; }
console.log("Response: " + response.statusCode);
});
Related
I'm trying to create an Azure function using nodeJS, but when I make a call to an https API I get an error message.
Is it possible to make a HTTPS call from azure function?
Here is my code
const https = require('https');
const querystring = require('querystring');
module.exports = async function (context, req) {
if (req.query.accessCode || (req.body && req.body.accessCode)) {
var options = {
host: 'api.mysite.com',
port: 443,
path: '/oauth/access_token',
method: 'POST'
};
var postData = querystring.stringify({
client_id : '1234',
client_secret: 'xyz',
code: req.query.accessCode
});
var req = https.request(options, function(res) {
context.log('STATUS: ' + res.statusCode);
context.log('HEADERS: ' + JSON.stringify(res.headers));
res.on('data', function (chunk) {
context.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
context.log('problem with request: ' + e.message);
});
req.write(postData);
req.end();
context.res = {
status: 200,
body: "Hello " + (req.query.accessCode)
};
} else {
context.res = {
status: 400,
body: "Please pass a name on the query string or in the request body"
};
}
context.done();
};
I get an error but I do not see any error on the console, also if I comment all the https call it works fine and I can see the Hello message on the screen.
Two points to fix
Delete context.done();. See Azure document.
If your function uses the JavaScript async function declaration (available using Node 8+ in Functions version 2.x), you do not need to use context.done(). The context.done callback is implicitly called.
Rename your https.request like var myReq = https.request(options, function(res).
There's a name conflict causing error as function has a built-in req object declared.
It's possible, here is an example of how to make a request to an Azure AD v2 token endpoint (I'd assume you are trying to do something similar):
var http = require('https');
module.exports = function (context, req) {
var body = "";
body += 'grant_type=' + req.query['grant_type'];
body += '&client_id=' + req.query['client_id'];
body += '&client_secret=' + req.query['client_secret'];
body += '&code=' + req.query['code'];
const options = {
hostname: 'login.microsoftonline.com',
port: 443,
path: '/ZZZ920d8-bc69-4c8b-8e91-11f3a181c2bb/oauth2/v2.0/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': body.length
}
}
var response = '';
const request = http.request(options, (res) => {
context.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
response += d;
})
res.on('end', (d) => {
context.res = {
body: response
}
context.done();
})
})
request.on('error', (error) => {
context.log.error(error)
context.done();
})
request.write(body);
request.end();
};
The difference is - the function is not async module.exports = function
I believe your issue is:
You should use the Node.js utility function util.promisify to turn error-first callback-style functions into awaitable functions.
link
In Azure function how to call an API using javascript. The request is POST with the header.I tried to use XMLHttpRequest, but i got exception like this XMLHttpRequest is not defined.
var client = new XMLHttpRequest();
var authentication = 'Bearer ...'
var url = "http://example.com";
var data = '{.........}';
client.open("POST", url, true);
client.setRequestHeader('Authorization',authentication);
client.setRequestHeader('Content-Type', 'application/json');
client.send(data);
Any other method is there to achive this,
You can do it with a built-in http module (standard one for node.js):
var http = require('http');
module.exports= function (context) {
context.log('JavaScript HTTP trigger function processed a request.');
var options = {
host: 'example.com',
port: '80',
path: '/test',
method: 'POST'
};
// Set up the request
var req = http.request(options, (res) => {
var body = "";
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
context.res = body;
context.done();
});
}).on("error", (error) => {
context.log('error');
context.res = {
status: 500,
body: error
};
context.done();
});
req.end();
};
You can also use any other npm module like request if you install it into your Function App.
I am writing my Node.js file now, which is to send requests to Yelp API and get the JSON response for client. I test my code in localhost.
I have seen the requesting url and both format and data are correct.
However, I get an error message when requesting this API:
connect ECONNREFUSED 127.0.0.1:443
Here is my Node.js code:
http.createServer(function (req, res) {
// data from the client
var some_data;
// send a GET request to Yelp’s API
var https = require('https');
var yelpMatch_url = encodeURI("https://api.yelp.com/v3/businesses/matches/best?some_data;
var headers = {
'Authorization': 'Bearer myAPI_KEY'
};
https.get({url: yelpMatch_url, headers: headers}, function(response) {
var body = '';
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
// write response json
res.write(body);
res.end();
});
}).on('error', function(e) {
console.log(e.message);
});
}).listen(myPort);
Why this error ?
It looks you are doing the request to https on your localhost.
Make sure your server is running locally, and update the get method as follows:
https.get(yelpMatch_url, {headers: headers}, function(req, response) {
var body = '';
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
// write response json
res.write(body);
res.end();
});
}).on('error', function(e) {
console.log(e.message);
});
Thanks! I figured it out. The format should be like this:
var https = require('https');
var myurl = "http://www.example.com";
var options = {
url: myurl,
headers: {
'Authorization': 'Bearer myKeyID'
}
};
https.get(options, function(response) {
... }
I am trying to maintain some old Node js code. I am having trouble in connecting to https url using corporate proxy.
Below code doesn't seem to work.
var https = require('https');
var options = {
hostname: 'PROXY_IP',
port : PROXY_PORT,
path : 'https://server.ourdomain.com/path/to/secure/api',
rejectUnauthorized : false,
headers: {
'Authorization': 'Basic ' + new Buffer('username:password').toString('base64'),
'Content-Type': 'application/json',
'Host' : 'https://server.ourdomain.com:443'
}
}
var responseChunk = '';
callback = function(response) {
if(response.statusCode !== 200) {
//Error occured. Handle error
}
response.on('data', function (chunk) {
responseChunk += chunk;
});
response.on('end', function () {
// Got complete response. Process and do something
});
}
var get_req = https.request(options, callback);
get_req.on('error', function(e) {
console.log("Error:" + e)
});
get_req.end();
Error after executing this is
Error:Error: socket hang up
I was able to get this working using request module. But not using https module.
What seems to be the problem?
Use request..
var request = require('request');
request({'url':'https://anysite.you.want/sub/sub','proxy':'http://yourproxy:8087'}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
})
As per title, how do I do that?
Here is my code:
var http = require('http');
// to access this url I need to put basic auth.
var client = http.createClient(80, 'www.example.com');
var request = client.request('GET', '/', {
'host': 'www.example.com'
});
request.end();
request.on('response', function (response) {
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
You have to set the Authorization field in the header.
It contains the authentication type Basic in this case and the username:password combination which gets encoded in Base64:
var username = 'Test';
var password = '123';
var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
// new Buffer() is deprecated from v6
// auth is: 'Basic VGVzdDoxMjM='
var header = {'Host': 'www.example.com', 'Authorization': auth};
var request = client.request('GET', '/', header);
From Node.js http.request API Docs
you could use something similar to
var http = require('http');
var request = http.request({'hostname': 'www.example.com',
'auth': 'user:password'
},
function (response) {
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
request.end();
var username = "Ali";
var password = "123";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var request = require('request');
var url = "http://localhost:5647/contact/session/";
request.get( {
url : url,
headers : {
"Authorization" : auth
}
}, function(error, response, body) {
console.log('body : ', body);
} );
An easier solution is to use the user:pass#host format directly in the URL.
Using the request library:
var request = require('request'),
username = "john",
password = "1234",
url = "http://" + username + ":" + password + "#www.example.com";
request(
{
url : url
},
function (error, response, body) {
// Do more stuff with 'body' here
}
);
I've written a little blogpost about this as well.
for what it's worth I'm using node.js 0.6.7 on OSX and I couldn't get 'Authorization':auth to work with our proxy, it needed to be set to 'Proxy-Authorization':auth
my test code is:
var http = require("http");
var auth = 'Basic ' + new Buffer("username:password").toString('base64');
var options = {
host: 'proxyserver',
port: 80,
method:"GET",
path: 'http://www.google.com',
headers:{
"Proxy-Authorization": auth,
Host: "www.google.com"
}
};
http.get(options, function(res) {
console.log(res);
res.pipe(process.stdout);
});
var http = require("http");
var url = "http://api.example.com/api/v1/?param1=1¶m2=2";
var options = {
host: "http://api.example.com",
port: 80,
method: "GET",
path: url,//I don't know for some reason i have to use full url as a path
auth: username + ':' + password
};
http.get(options, function(rs) {
var result = "";
rs.on('data', function(data) {
result += data;
});
rs.on('end', function() {
console.log(result);
});
});
I came across this recently.
Which among Proxy-Authorization and Authorization headers to set depends on the server the client is talking to.
If it is a Webserver, you need to set Authorization and if it a proxy, you have to set the Proxy-Authorization header
This code works in my case, after a lot of research. You will require to install the request npm package.
var url = "http://api.example.com/api/v1/?param1=1¶m2=2";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
exports.checkApi = function (req, res) {
// do the GET request
request.get({
url: url,
headers: {
"Authorization": auth
}
}, function (error, response, body) {
if(error)
{ console.error("Error while communication with api and ERROR is : " + error);
res.send(error);
}
console.log('body : ', body);
res.send(body);
});
}
For those not using DNS and needs more depth (you can also use request instead of get by simply replacing get with request like so: http.request({ ... })):
http.get({
host: '127.0.0.1',
port: 443,
path: '/books?author=spongebob',
auth: 'user:p#ssword#'
}, resp => {
let data;
resp.on('data', chunk => {
data += chunk;
});
resp.on('end', () => console.log(data));
}).on('error', err => console.log(err));
This is not well documented in Node.js, but you can use
require("http").get(
{
url: "www.example.com",
username: "username",
password: "mysecret",
},
(resp) => {
let data;
resp.on("data", (chunk) => (data += chunk));
resp.on("end", () => console.log(data));
}
)
.on("error", (err) => console.log(err));
Since the got pacakge inherits it's options object from http.request, username and password is also available there.