Can't get body response with Node from RESTFUL API - javascript

I'm tring to get a body response from a RESTFUL API using Node.js and it's "request" lib to send a GET request. Here's the code:
const request = require('request');
const url = 'https://myurl.com';
const headers = {
'x-functions-key': 'mysecretkey'
};
request.get(`${url}${headers}`, (err, response, body) =>{
if (err){
console.log(err)
}
console.log(body)
})
But when I run "node myfile" I get no response from the body, the console return is blank. I think I'm missing something. I've tested the URL and key with Postman and it's working fine, the JSON response appears to me there.
Obs.: I'm new to Node, tried with this tutorial: https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html. The "url" and "key are masked here for security reasons. Any help is fine to me, I'm grateful.

The issue is that you can't just put headers inside the template string. You need to specify them with an options object.
request.get({ url: url, headers: headers }, (err, response, body) => { ... });
Or, with ES6 shorthand:
request.get({ url, headers }, (err, response, body) => { ... });

The problem is that on request.get line you have your URL and headers templates
`${url}${headers}`
Here's the documentation regarding custom headers
So the solution would be creating an options variable like this:
const options = {
url: 'https://myurl.com',
headers: {
'x-functions-key': 'mysecretkey'
}
};
And then passing it to request
request.get(options, (err, response, body) =>{
if (err){
console.log(err)
}
console.log(body)
})
Hope this helps

Related

Nodejs PUT/PATCH is not working with axios and request but same works from Postman

I am trying to make some modifications to my Rest API by making the PUT request using request package but it does not seem to work so. Although I am able to make the modifications to the same API using the same JSON body using the Postman. Also, I am not getting any errors so not understanding what's wrong.
Since request was not working, I tried axios even with that no response no error. Following is my sample code which is making request to my Rest API:
const request = require('request');
const axios = require('axios');
const https = require('https');
request(
{
url: testIdUrl,
method: 'PUT',
agentOptions: {
rejectUnauthorized: false
},
headers: [{
'content-type': 'application/json',
body: JSON.stringify(requestBody)
}]
},
function(error, response, body) {
if(error){
console.log("SOMETHING WENT WRONG")
console.log(error)
}
console.log("RESPONSE FROM TEST ID PUT")
})
axios.put(testIdUrl, requestBody)
.then((res) => {
console.log(`Status: ${res.status}`);
console.log('Body: ', res.data);
}).catch((err) => {
console.error(err);
});
Can someone please help me understand what's wrong with the code? Does my Rest API include all the tokens and information? When I use the same requestBody and URL then its works in POSTMAN.

Retrieve redirectUri from npm Request

I'm trying to retrieve some information from the response that npm Request generated. I'm able to retrieve information like "statusCode" by typing "response.statusCode". However if I want to retrieve other information like "redirectUri", it would show undefined. How am I able to retrieve "redirectUri"?
Below is the code to get the response from the URL that I'm testing;
var request = require('request');
var getRequest = function (url, index) {
request(url, function (error, response, body) {
console.log(response.redirectUri);
});
}
getRequest('https://www.exampleUrl.com', 1);
Below are some of the information from the response;
redirects: [
{ statusCode: 302,
redirectUri:'https://www.exampleurl'.....etc
}],
Please see the response in attached image
Note: I have blurred out the url that I'm testing.
I found my answer from How do I get the redirected url from the nodejs request module?. Set "followRedirect: false" and use "response.headers.location".
var url = 'http://www.google.com';
request({ url: url, followRedirect: false }, function (err, res, body) {
console.log(res.headers.location);
});

Chunked base64 string, piece by piece using http nodejs

From my API(nodejs), I'm accessing a third-party API (using http) to download files.
The service returns a Base64 string, chopped into smaller pieces, to be able to handle larger files.
Is it possible to do multiple http-requests (loop ?) to the third-party service, send each piece in response, to the browser until there is no longer any response from the third-party service?
The reason i want to do this, is because I don't want to consume to much memory on the node server.
I will put the pieces back together in the browser.
Any suggestions on how to do this?
See my current code below.
var request = require('request');
router.post('/getfiledata', function(req, res) {
var fileid = req.body.fileid;
var token = req.headers.authorization;
getFileData(req, res, dbconfig, fileid, token, function(err, chunkOfFile) {
if (err) {
res.status(500).send({
status: 500,
message: err
});
return;
}
res.send(chunkOfFile);
});
});
function getFileData(req, res, dbconfig, fileid, token, next) {
var url ="http://*ip*/service/rest/getfiledata";
var reqbody = {
fileId: fileid
};
var options = {
url: url,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': token
},
json: true,
body: reqbody
};
/*SOME LOOP HERE TO GET EACH CHUNK AND SEND TO BROWSER*/
request(options, function(err, resp, body) {
if (err) {
console.log(err);
next(err, undefined);
return;
} else {
next(undefined, body)
};
});
};
I think you need Socket.io to push chunks to the browser.
Server :
socket.send("chunk", chunkOfFile)
Client :
let fullString = ""
socket.on("chunk", chunkOfFile => fullString += chunkOfFile )
Something like that
The request library you are using allows for streaming of data from one source to another. Check out the documentation on github.
Here is an example from that page:
request
.get(source)
.on('response', function(response) {
console.log(response.statusCode) // 200
console.log(response.headers['content-type']) // 'image/png'
})
.pipe(request.put(destination))
You may choose to use the http module from Nodejs, as it implements the EventEmitter class too.
I ended up doing a recursive loop from the client. Sending http-requests to my API(node) until the response no longer returns any base64 data chunks.
Thank you guys!

Express Nodejs - How to pass request.files to another POST request

I have a page where user uploads files and are passed to Node API which does some operations like database insert and finally has to send the files to another node rest API for virus check.
I can see file content and attributes in req.files in the first API call but struggling to pass req.files to another node API URL using request.post.
var uploadFile= function(req, res) {
var files = req.files.upload;
Async.series(
[ function (callback) {..},
function (callback){viruscheck(files,callback);}
....
//viruscheck method
var viruscheck= function(files, callback) {
request.post({url: "http://loclahost:1980/viruscheck/upload.json",
qs: {
..
},
headers: {'enctype-type': 'multipart/form-data'},
form:{
upload:files
}
},function(error, response, body){
if(error) {
console.log(error);
callback(error)
} else {
console.log(response.statusCode, body);
callback()
}
});
}
In API http://loclahost:1980/viruscheck/upload.json I see file content in body rather than req.files.
How can I get the files in request.files in my second API call?
Use:
headers: {'Content-Type': 'multipart/form-data'},
Instead of:
headers: {'enctype-type': 'multipart/form-data'},
enctype is an HTML form thing.
See this answer for more:
Uploading file using POST request in Node.js

How to get all pages from facebook account

I have tried to get all facebook pages list. But I got an error.
Error is : request is not defined
Code :
var url = 'https://graph.facebook.com/me/accounts';
var accessToken = req.user.facebookAccessToken;
var params = {
access_token: accessToken,
};
request.get({ url: url, qs: params}, function(err, resp, pages) {
// console.log(resp);
pages = JSON.parse(pages);
})
The error you're getting isn't related to Facebook.
"request is not defined" means you're trying to do something with the variable request (call its .get() function in this case) but the variable request hasn't been set anywhere.
Your tags indicate this is in Node. Do you have this line already?
var request = require('request');
If not, add that before the code in your question. That loads the 'request' module you're trying to use.
You got the issue on request ,,
install npm request
require('request').get({
uri: url,
headers: {'content-type': 'application/x-www-form-urlencoded'},
body: require('querystring').stringify(params)
}, function (err, resp, body) {
})

Categories

Resources