Access HTTP Response Body on Axios GET Request Error - rest

We are making a simple HTTP GET request to an API & noticing that when our HTTP requests error, the response body sometimes has more details then the error message. We are using the axios. We would like to access both the response and the error message from our code, but we are only seeing the error message and are unsure how to access the response. Here is our code:
Calling the API:
import { httpClient } from '../httpClient'; //AxiosInstance
type GetLocations = () => Promise<AxiosResponse<ILocation[]>>
const getLocations: GetLocations = async () => {
const url = `/Location`;
return httpClient.get(url);
}
const callAPI = async () => {
try {
const axiosResponse = await getLocations();
console.log(axiosResponse.data);
catch(error) {
// error.message has the error message, but we would like access to the http response body as well.
console.log(error)
}
}
Some Screenshots:
console.log(error):
The error object as JSON:
DevTools > Network > Our API Call > Response from same request that errored (has more info):
We would like to access this Incorrect syntax near ','. response from our catch block.

Related

Axios error when sending api request to Discord

I'm trying to send an automated message to discord from my account token using the axios client, it worked on a different project of mine but it doesn't work on a brand new project for some reason. Here is the code so far:
const axios = require('axios').default;
async function Post() {
const URL = `https://discord.com/api/v9/channels/${process.env.CHANNEL}/messages`
const payload = { content: "This message has been sent using axios!" }
await axios.post(URL, payload, { headers: { 'authorization': process.env.TOKEN } })
}
Post();
This is the error I'm getting:
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
TypeError [ERR_HTTP_INVALID_HEADER_VALUE]: Invalid value "undefined" for header "authorization"
at ClientRequest.setHeader (node:_http_outgoing:579:3)
at new ClientRequest (node:_http_client:256:14)
at Object.request (node:https:353:10)
at RedirectableRequest._performRequest (/home/nonce/Documents/Repositories/test/node_modules/follow-redirects/index.js:279:24)
at new RedirectableRequest (/home/nonce/Documents/Repositories/test/node_modules/follow-redirects/index.js:61:8)
at Object.request (/home/nonce/Documents/Repositories/test/node_modules/follow-redirects/index.js:482:14)
at dispatchHttpRequest (/home/nonce/Documents/Repositories/test/node_modules/axios/lib/adapters/http.js:232:25)
at new Promise (<anonymous>)
at httpAdapter (/home/nonce/Documents/Repositories/test/node_modules/axios/lib/adapters/http.js:48:10)
at dispatchRequest (/home/nonce/Documents/Repositories/test/node_modules/axios/lib/core/dispatchRequest.js:58:10) {
code: 'ERR_HTTP_INVALID_HEADER_VALUE'
}
And for the record, I'm not trying to create a spammer or anything that breaks Discord's API rules.
Here are the versions I'm using, if it helps in any way:
node: v16.13.2
npm: v8.1.2
axios: v0.25.0
Found the error, I forgot to add the dotenv package all along.

axios interceptor: need to undestand the javascript code

I am trying to understand this code. And also how to use it
https://stackoverflow.com/a/53294310/2897115
createAxiosResponseInterceptor() {
const interceptor = axios.interceptors.response.use(
response => response,
error => {
// Reject promise if usual error
if (errorResponse.status !== 401) {
return Promise.reject(error);
}
/*
* When response code is 401, try to refresh the token.
* Eject the interceptor so it doesn't loop in case
* token refresh causes the 401 response
*/
axios.interceptors.response.eject(interceptor); <---- What does this do
return axios.post('/api/refresh_token', {
'refresh_token': this._getToken('refresh_token')
}).then(response => {
saveToken();
error.response.config.headers['Authorization'] = 'Bearer ' + response.data.access_token;
return axios(error.response.config); <--- what does this do
}).catch(error => {
destroyToken();
this.router.push('/login');
return Promise.reject(error);
}).finally(createAxiosResponseInterceptor);
}
);
}
Generally i use axios script with access_token is as:
const url = "dj-rest-auth/password/change/";
const auth = {
headers: {
Authorization: "Bearer " + localStorage.getItem("access_token"),
Accept: "application/json",
"Content-Type": "application/json",
},
};
const data = {
old_password: old_password,
new_password1: new_password1,
new_password2: new_password2,
};
const promise = axios.post(url, data, auth);
promise
.then((res) => {
console.log(res)
})
.catch((err) => {
if (err.response) {
console.log(`${err.response.status} :: ${err.response.statusText}`)
console.log(err.response.data)
}
})
And in this code how to use the interceptor
Eject interceptor
axios.interceptors.response.eject(interceptor); <---- What does this do
Internally, interceptors.response is an array of interceptors, the method axios.interceptors.response.use return the id of the new interceptor. Calling eject passing the id of the interceptor will set the corresponding item in the array to null, and the interceptor has no effect anymore.
When we receive the response code 401, we use the interceptor to send another request to get the token. To avoid the infinity loop if the latter also receives the response code 401, we eject the interceptor in this case.
Resend original request
return axios(error.response.config); <--- what does this do
After receiving the token, we want to resend the original request, its configuration is stored in error.response.config according to the response schema
To use the function, call it before sending the request. (People talk about it in the thread of the accepted answer.)

axios DELETE request with body in Nuxt.js

I have an app built with Nuxt.js. To get data from the API I use axios, namely #nuxtjs/axios. All request work fine but for the DELETE method.
My syntax is the following:
async removeItemFromCart(productId) {
const accessKey = await this.$store.dispatch('fetchUserAccessKey');
try {
this.$axios.delete(`/api/baskets/products?userAccessKey=${ accessKey }`, {
data: {
productId: productId
}
})
} catch (error) {
console.log(error);
}
},
However, in the console I always get the following error: createError.js?2d83:16 Uncaught (in promise) Error: Request failed with status code 400
I tried to use params instead of data, but to no avail. What am I missing here?
It seems that there's an issue with axios: when you use delete method with body, it either doesn't include payload, or deletes Content-type: 'application/json' from headers. To solve the issue, I used .request instead of .delete (according to https://github.com/nuxt-community/axios-module/issues/419)
this.$axios.request(`/api/baskets/products?userAccessKey=${ accessKey }`, {
data: {
productId: productId
},
method: 'delete'
}).

Error when trying to authorize Axios get request

I am trying to access the Uber API with Axios and I am running into some trouble. I have plugged this data into Postman and I get a 200 response code with no problems. However, when I try to make an Axios call, I get response code 401 unauthorized. Can I get some help looking through my code to find out why my authorization is not working correctly with Axios?
Here is a link to the Uber API docs I am referencing. Uber API Reference
getRide_Uber = async (addressOrigin, addressDestination) => {
let origin = await geocodeAddress(addressOrigin);
let destination = await geocodeAddress(addressDestination);
const url = "https://api.uber.com/v1.2/estimates/price";
const params = {
params: {
start_latitude: origin.lat,
start_longitude: origin.lon,
end_latitude: destination.lat,
end_longitude: destination.lon
}
};
const headers = {
headers: {
Authorization: `Token ${process.env.UBER_SERVER_TOKEN}`
}
};
const response = await axios
.get(url, params, headers)
.then(function(response) {
data = response.data;
})
.catch(function(error) {
console.log(error);
});
return data;
};
Please let me know if anything needs clarification. Thanks!
try below syntax,
const config = {
headers: {
Authorization: `Token ${process.env.UBER_SERVER_TOKEN}`
}
params: {
start_latitude: origin.lat,
start_longitude: origin.lon,
end_latitude: destination.lat,
end_longitude: destination.lon
}
};
const response = await axios
.get(url, config)
.then(function(response) {
data = response.data;
})
.catch(function(error) {
console.log(error);
});
return data;
There is one more aspect axios, async/await is not supported in Internet Explorer and older browsers. So also please check your browser versions as well.
Not sure how are you getting token from env but seems the server token is not getting pass correctly, may be few extra characters while reading from env. Try to run the program first with hard coded token in program itself and once you are sure its not code issue, you can move it into config/env and then debug env read issue.

Request to Graph API returns 400 Bad Request response; expecting Graph API error code

We are sending a request to facebook's Graph API to update an Ad Set's end_time via JavaScript using the node-fetch npm package:
const data = {
end_time: fields.endTime,
access_token: FB_ADS_TOKEN
}
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}
const url = `${FB_GRAPH_ENDPOINT}/${fields.adSetId}`
return fetch(url, options)
.then(response => {
if (response.status != 200) {
throw `status: ${response.status} - ${response.statusText}`
}
When sending a data value that I expect to give me a code 100, subcode 1885272 (Invalid parameter, Budget too low), response.status is 400 and response.statusText is Bad Request.
The same request url used in the Graph API Explorer yields the expected error code. The url is good, as it successfully updates with an end_time that meets the criteria for budget.
How can I get the correct Graph API error code?