I am using the Axios version 0.21.1.
I am sending HTTPS get request as below.
When I run below code, the #2 line inside the try block console.log... throws error.
But the error object I get in catch is empty. Not sure why log is throwing error.
try {
let getRes = await axios.get(myUrl, {headers: {'Authorization': `Bearer ${token}`}});
console.log("getRes: " + JSON.stringify(getRes));
} catch (error) {
console.log("Error: " + JSON.stringify(error));
}
If I run the following version with #2 parameter as {} or null for axios.get.
I get the error printed in catch but I am not sure why it is failing.
try {
let getRes = await axios.get(myUrl, {}, {headers: {'Authorization': `Bearer ${token}`}});
console.log("getRes: " + JSON.stringify(getRes));
} catch (error) {
console.log("Error: " + JSON.stringify(error));
}
The error I get is 401 Unauthorized.
From the Postman, this URL is working fine with the same Bearer token as I am using from the code.
I have even tried the below code, with the behavior same as #1 case:
let getrRes = await axios({
method: 'get',
url: myUrl,
headers: {
"Authorization": "Bearer "+token
}
});
I don't want to have request body for this get request.
What can be the issue and how to call axios.get correctly?
Your first program is the right one! But inside it's your console.log() that is not good: you cannot use the JSON.stringify() method on the getRes object returned by axios, that's why your program goes into the catch.
To display the response, either don't use JSON.stringify(), or use JSON.stringify() on the data returned by axios (which is getRes.data)
try {
let getRes = await axios.get(myUrl, {headers: {'Authorization': `Bearer ${token}`}});
console.log("getRes: " + JSON.stringify(getRes.data));
// OR
console.log("getRes: " + getRes);
} catch (error) {
console.log("Error: " + error);
}
Note that you can't use the JSON.stringify() on the error that you got in the catch either! That's why you only had an empty object.
If you want to identify the exact cause of error, change the console.log in your try catch block. Don't try to JSON.strigify the error, rather just dump it onto the console. This will make sure to dump the error as-is, onto the console.
try {
let getRes = await axios.get(myUrl, {headers: {'Authorization': `Bearer ${token}`}});
console.log("getRes: " + JSON.stringify(getRes));
} catch (error) {
console.log(error);
}
If you still wish to get a fine grained error message, you can convert the error into string by using one of the following statements inside your catch clause:
console.log(error.message);
console.log(error.toString());
Related
I'm working on a custom integration solution using Express routes and after making a fetch call to firebase I need the response to my server to be the one coming from firebase to show me any issues (such as authentication errors) coming from there.
I've been trying to display the response by using res.send(), but it throws me a "TypeError: Converting circular structure to JSON" error, but when console.logging that same response it gives me the correct response (which is an authentication error). What's the deal with that?
Here's the code:
router.route("/bankval").get (fetchAirtabeleRecords, (req, res) => {
fetch(`https://xxxxxxxxxxxx.firebaseio.com/integratedData.json?auth=${FIREBASESECRET}`,{
method: 'PUT',
headers:
{
Authorization: 'Bearer ' + FIREBASESECRET,
'Content-Type': 'application/json'
},
body: JSON.stringify({bankValuation: res.bankVal}) // correct values here
})
.then((res) => res.json())
.then(res.send(res)) // This throws me the error
.then((res)=> { console.log('response: ', res); }) // This works and displays expected "error: 'Unauthorized request.' from firebase, but it's only in console, so it's not good enough."
// .then(res.send({bankValuation: res.bankVal})) // this works, but if authentication error occurs it still displays the correct data, when it's obviously not sent to firebase. Only using this for testing purposes.
.catch(err=> { console.log('error: ',err); }) })
I'm pretty new to this, so maybe I'm doing this completely backwards or something, but any input is appreciated.
Thanks.
You override res, so try this:
.then((resp) => resp.json())
.then((resp) => res.send(resp))
.then((resp)=> { console.log('response: ', resp); })
I am trying to fetch the results from all repositories of my organisation under a search category. The results are fetched properly when I use the curl command as shown below
curl -H "Authorization: token ****" -i https://api.github.com/search/code?q=org:<org>+<search_param>
But when I try to run it programmatically in nodejs via the request module it is not returning any results.
My code is as shown below
const request = require("request");
const options = {
url:'https://api.github.com/search/code?q=org:<org>+<search_param>'
headers: {
"Autorization": "token ***",
"User-Agent": "request"
},
json:true
}
console.log(options);
request.get(options, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
The output for the above code is as below
body: {"total_count":0,"incomplete_results":false,"items":[]}
Please let me know what is wrong with the above code or if I am missing anything.
I was able to solve this by using the axios module instead of request module as the request module does not send the Authorization hader. Got a reference from Nodejs request module doesn't send Authorization header.
The updated code which works is as follows
const axios = require("axios");
const options = {
method:"get",
url:'https://api.github.com/search/code?q=org:<org>+<searchtoken>',
headers: {
"Authorization": "token ***",
"User-Agent": "abc"
}
}
console.log(options);
axios(options).then(function ( response) {
console.log('statusCode:', response); // Print the response status code if a response was received
// console.log('body:', body); // Print the HTML for the Google homepage.
}).catch(function (error) {
console.log(error);
});
Thanks #mehta-rohan for the help
Recently, I encountered a problem while trying to issue a request using NodeJS and request-promise.
The following code is nested inside a multer call for file uploading (using nested functions / clusters.
const options = {
method: 'POST',
uri: 'URL of your choice',
body: {
//Body of the request
},
// json: true,
headers: {
// 'Content-Type': 'application/x-www-form-urlencoded',
},
}
request(options)
.then(function (response) {
console.log('Response: ', response);
})
.catch(function (err) {
console.log('Error: ', err);
});
While using the current request, without the 'json: true' property (commented out), I get the following error:
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Received type object
at write_ (_http_outgoing.js:603:11)
at ClientRequest.write (_http_outgoing.js:575:10)
at Request.write (PATH/node_modules/request/request.js:1500:27)
at end (PATH/node_modules/request/request.js:549:18)
at Immediate.<anonymous> (PATH/node_modules/request/request.js:578:7)
at runCallback (timers.js:696:18)
at tryOnImmediate (timers.js:667:5)
at processImmediate (timers.js:649:5)
at process.topLevelDomainCallback (domain.js:121:23)
And when I turn the 'json: true' option on, the problem doesn't occur, but the remote API returns an error as it doesn't handle JSON requests/their added curly braces well.
Any ideas about getting over this issue?
Thank you.
Solved it!
As the remote host doesn't handle JSON well, and required "ordinary" POST request to be sent, I looked again inside request-promise's documentation.
By changing body{} to formData{}, and commenting out json: true, the problem was solved.
const options = {
method: 'POST',
uri: 'URL of your choice',
formData: {
//Request's data
},
}
request(options)
.then(function (response) {
console.log('Response: ', response);
})
.catch(function (err) {
console.log('Error: ', err);
});
Try Below -
url = "your url"
const options = {
url: url,
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-Charset': 'utf-8'
},
body: {
}
};
request.post(options, function (err, response, body) {
// do something with your data
console.log(response.statusCode);
console.log(body)
});
I faced similar issue, for my case, upload directory was not properly defined, make sure the path to which you want to upload file exists and is clearly defined
I'm using a forEach loop to make a request to two different paths, but, although it does console.log() both bodyResponses, it gives error when trying to save it to render "index.ejs" with its value. (index.ejs is the template I wanna render):
manyPaths.forEach(function (element){
var signature = crypto.createHmac('sha256', apiSecret).update(verb + element.path + expires).digest('hex');
var headers = {
'content-type' : 'application/json',
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'api-expires': expires,
'api-key': apiKey,
'api-signature': signature
};
const requestOptions = {
headers: headers,
url:'https://testnet.bitmex.com'+element.path,
method: verb
};
request(requestOptions, function(error, response, bodyResponse) {
if (error) {
console.log(error);
} else {
console.log(bodyResponse);
bodyResponse=JSON.parse(bodyResponse);
res.render("index", {bodyResponse:bodyResponse});
}
});
});
it does console.log both responses, but I get this error for render():
Error: Can't set headers after they are sent.
You can respond to a HTTP request only ONCE. So in your FOR loop, the first response is sent,and the connection is closed, and when it comes to the second iteration it fails with the error you see.
You have to wait for both calls to complete in parallel, and then kick of a function to send the response .
Following my previous post, I am getting
XHR finished loading: POST "http://partners.api.skyscanner.net/apiservices/pricing/v1.0".
seems the POST is working correctly, but for GET:
GET
http://testdomain.com:3000/undefined?apiKey=APIKEY&stops=0&duration=360&includeCarriers=ba;u2;af
404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (bundle.js:23687)
at settle (bundle.js:23657)
at XMLHttpRequest.handleLoad (bundle.js:23529)
here is that part of the code:
axios(authOptions)
.then(function(response){
console.log("response ====> ", response.headers);
console.log("--->", response.headers.Location);
/*
console.log("data is: ", response.data);
console.log("response.request.responseURL: ", response.request.responseURL );
console.log("response headers", response.headers);
console.log("location headers: ", response.headers.location);
*/
var newAuthOpts = {
method: 'GET',
url: response.headers.Location + '?apiKey=APIKEY&stops=0&duration=360&includeCarriers=ba;u2;af',
data: querystring.stringify(data),
json: true
};
axios(newAuthOpts).then(function(response) {
console.log(response);
});
})
.catch(function(error){
console.log(error);
});
return {
type: FETCH_LOCALS,
payload: data
};
I am trying to get the correct url from the header: response.headers.location, but this returns undefined, I can not find the error. can some one help please?
There's a big difference between response.headers.location and response.headers.Location - everything in JavaScript is case-sensitive. In other words both versions could co-exist and be treated as completely different properties. It's for this reason that camelCase is commonly used. In that way we can easily recognise it as an error when, for example, a property begins with a capital letter.