'How to send body data and headers with axios get request?
I've tried
axios.get(url, {headers:{},data:{}})
But it doesn't work with this.
Solution 1:[1]
As far as I know you can't send body data with GET request. With get you can have only Headers. Just simply change to POST and then you can do something like this :
const bodyParameters = {
key: "value",
};
const config = {
headers: { Authorization: `Bearer ${userToken}` },
};
axios.post("http://localhost:5000/user", bodyParameters, config)
.then((res)=> {
console.log(res)
})
.catch((err) => console.log(err));
};
or if you want to send headers with GET request
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
Solution 2:[2]
// data
is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
Solution 3:[3]
You should refer to https://github.com/axios/axios#request-config
Check the section for data and header.
Solution 4:[4]
You can try this:
const getData = async () => {
try {
const response = await axios.get(`https://jsonplaceholder.typicode.com/posts`, {
method: 'GET',
body: JSON.stringify({
id: id,
title: 'title is here',
body: 'body is here',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
console.warn(response.data);
} catch (error) {
console.warn(error);
}
}
Solution 5:[5]
axios.get(
BASEURL,
{
params: { user_id: userId },
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
},
);
Solution 6:[6]
yeah, it's true it doesn't work to send body in Axios get even if it works in the postman or the backend.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ili |
Solution 2 | Ivan Camilito Ramirez Verdes |
Solution 3 | Ayushya |
Solution 4 | Khabir |
Solution 5 | PR7 |
Solution 6 | Shehab_Mind |