Home > Software engineering >  Nodejs axios.get error when sending HTTPS get request
Nodejs axios.get error when sending HTTPS get request

Time:05-20

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?

CodePudding user response:

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.

CodePudding user response:

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