axios DELETE request with body in Nuxt.js - axios

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

Related

CORS error: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response

I'm trying to fetch an image resource that's part of a conversation message.
I've tried both FETCH as well as using AXIOS but I'm getting the same error message.
Here's an example of my FETCH request
const token = `${accountSid}:${authToken}`;
const encodedToken = Buffer.from(token).toString('base64');
let response = await fetch('https://mcs.us1.twilio.com/v1/Services/<SERVICE_SID>/Media/<MEDIA_SID>',
{
method:'GET',
headers: {
'Authorization': `Basic ${encodedToken}`,
}
});
let data = await response.json();
console.log(data);
And here's what Axios looked like
let config = {
method: 'get',
crossdomain: true,
url: 'https://mcs.us1.twilio.com/v1/Services/<SERVICE_SID>/Media/<MEDIA_SID>',
headers: {
'Authorization': `Basic ${encodedToken}`,
},
};
try {
const media = await axios(config);
console.dir(media);
} catch(err) {
console.error(err);
}
Both ways are NOT working.
After looking into it more, I found out that Chrome makes a pre-flight request and as part of that requests the allowed headers from the server.
The response that came back was this
as you can see, in the "Response Headers" I don't see the Access-Control-Allow-Headers which should have been set to Authorization
What am I missing here?
I have made sure that my id/password as well as the URL i'm using are fine. In fact, I've ran this request through POSTMAN on my local machine and that returned the results just fine. The issue is ONLY happening when I do it in my code and run it in the browser.
I figured it out.
I don't have to make an http call to get the URL. It can be retrieved by simply
media.getContentTemporaryUrl();

How to get headers from AxiosResponse-Observable?

Using NestJS, Axios returns an Observable<AxiosResponse>.
How can I get the headers of a GET- or HEAD-Request?
Lets say I make a HEAD-request:
import { HttpService } from '#nestjs/axios';
const observable = this.httpService.head(uri);
How can I get the headers from the result?
Update:
I found a nice workaround that just works with a single line of code.
There is another library called https with is more powerful:
import http from "https";
await http.request(uri, { method: 'HEAD' }, (res) => {
console.log(res.headers);
}).on('error', (err) => {
console.error(err);
}).end();
The headers of the response are available in the subscribe callback with the headers property.
this.httpService.head(uri).subscribe(res => {
console.log(res.headers)
});
Playground
According to https://github.com/axios/axios#request-config:
For request headers you should use something like this:
this.httpService.axiosRef.interceptors.request.use(function (config) {
// Do something before request is sent
console.log(config);
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
You should use it onModuleInit (to prevent working a few interceptors in a time)
Also you can make own module like in this answer: https://stackoverflow.com/a/72543771/4546382
For the response headers you can just use response.headers

React useQuery - useMutation onError not catching

I'm using a combination of Axios and react-query to make a POST request to a server that may answer with response code 400 and validation errors.
export const axiosDefault = axios.create({
baseURL: API_LINK,
headers: {
'Content-Type': 'application/json'
},
})
const contactMutation = useMutation(
(data) => axiosDefault.post('/contact', data),
{
onSuccess: (response) => {
console.log('Success', response)
},
onError: (error) => {
console.log('Error', error)
}
}
)
However, when calling contactMutation.mutate(someData) the error response from the server does not get processed by the react query library and instead propagates upward. Neither the onSuccess or onError handlers get called, the isError property of the mutation is also not set.
I've spent hours tearing my hair out over this, what am I doing wrong?
hi i also had same issue i solved by wrapping api function to try/catch block and throw the catched Error.
(data) => {
try {
axiosDefault.post('/contact', data),
} catch (error) {
throw error
}
}

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.

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.