using Node.js to make request, Yelp API error - node.js

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) {
... }

Related

Create a API endpoint in NodeJS to make REST api call and return a JSON data

So I need to create a endpoint i.e. A GET request in NodeJS which will make a curl call to another api and return a data. I am using native method of NodeJS to make curl call using https module. But I am not getting any response when I hit my nodeJS api (i.e. /api/mailers/campaigns). If I try to print curl response in console it returns me correct data. Is there anything I am missing?
Basically for security purpose I will hit my nodejs endpoint from my frontend
const app = express();
const http = require("https");
app.get('/api/mailers/campaigns', (req, res) => {
var chunks = [];
var options = {
"method": "GET",
"hostname": "api.mailerlite.com",
"port": null,
"path": "/api/v2/campaigns",
"headers": {
"x-mailerlite-apikey": "api_key",
"content-type":"application/json"
}
};
var req = http.request(options, function (res) {
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
return body.toString();
});
});
req.end();
})
No response I got from any one but Genius me found a solution by self :P
Just need to send response in req.end() method and it works fine
resp.on("end", function () {
var body = Buffer.concat(chunks);
res.send(JSON.parse(body))
});
Complete solution
app.get('/api/mailers/campaigns', async(req, res) => {
var chunks = [];
var options = {
"method": "GET",
"hostname": mailerBaseUrl,
"path": "/api/v2/campaigns?limit=100",
"headers": {
"x-mailerlite-apikey": mailerApiKey
}
};
var req = await http.request(options, function (resp) {
resp.on("data", function (chunk) {
chunks.push(chunk);
});
resp.on("end", function () {
var body = Buffer.concat(chunks);
res.send(JSON.parse(body))
});
});
req.end();
});

In azure functions using javascript how to call send request to a endpoint

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.

node.js http set request parameters

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);
});

Node.js https.request not returning data as expected

I'm trying to proxy API requests to a sever using node's https.request() function. When I run the same request to the same endpoints with the same headers through Postman I get the data back as expected. When I run the request though the node proxy I get http 500 error codes back. Is there anything obviously wrong with the way I'm sending the requests:
#!/usr/bin/env node
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
var https = require('https'),
connect = require('connect'),
staticDir = 'target/ui';
var app = connect();
app.use(connect.logger('dev'))
.use(connect.bodyParser())
.use(function(req, res, next){
if( /^\/api\//.test(req.url) ){
var options = {
hostname: 'host.name',
port: 9090,
path: req.url,
method: req.method,
headers: {
authorization: 'Basic XYZ123',
'content-type': 'application/json',
accept: 'application/json, text/javascript, */*; q=0.01',
}
};
var proxyRequest = https.request(options).on('response', function(res){
var data = "";
res.on('data', function(chunk){
data += chunk;
})
res.on('end', function(){
sendData(data);
});
res.on('error', function(e){
console.log('ERROR: ', e);
sendError(e, code);
})
})
proxyRequest.end();
function sendData(data){
console.log('SENDING RESPONSE DATA', data)
res.write(data);
res.end();
}
function sendError(msg, code){
res.end(msg, code)
}
}
else {
next();
}
})
.use(connect.static(staticDir));;
app.listen(9090);

How to save response returned as application/pdf

I am making an API call to SmartSheet that returns the worksheet as a PDF file.
This is the relevant documentation - link
My question is how do I accept the PDF response and save it locally in nodeJs? I am making use of the https module and I know how to make the request, but I can't understand how do I accept the response:
https.request(options, function (response) {
var body = '';
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
//What do I do with the body here?
});
});
That depends. How do you want store downloaded PDFs? If you want to store them in local file system, then you can stream data directly into the file.
For example:
var fs = require('fs');
var https = require('https');
var options = {
hostname: 'google.com',
port: 443,
path: '/',
method: 'GET'
};
var req = https.request(options, function (response) {
response.on('end', function () {
// We're done
});
response.pipe(fs.createWriteStream('/path/to/file'));
});
req.end();
req.on('error', function (err) {
// Handle error here
});

Resources