Axios API is a bit different from the jQuery AJAX one. If you have to pass some params along with GET request, you need to use params property of config object (the second param of .get() method):
axios.get('/api/updatecart', {
params: {
product: this.product
}
}).then(...)
You can pass either a plain object or a URLSearchParams object as params value.
Note that here we're talking about params appended to URL (query params), which is explicitly mentioned in the documentation.
If you want to send something within request body with GET requests, params won't work - and neither will data, as it's only taken into account for PUT, POST, DELETE, and PATCH requests. There're several lengthy discussions about this feature, and here's the telling quote:
Unfortunately, this doesn't seem to be an axios problem. The problem seems to lie on the http client implementation in the browser javascript engine.
According to the documentation and the spec XMLHttpRequest ignores the body of the request in case the method is GET. If you perform a request in Chrome/Electron with XMLHttpRequest and you try to put a json body in the send method this just gets ignored.
Using fetch which is the modern replacement for XMLHtppRequest also seems to fail in Chrome/Electron.
Until it's fixed, the only option one has within a browser is to use POST/PUT requests when data just doesn't fit into that query string. Apparently, that option is only available if corresponding API can be modified.
However, the most prominent case of GET-with-body - ElasticSearch _search API - actually does support both GET and POST; the latter seems to be far less known fact than it should be. Here's the related SO discussion.
HTTP GET request with a body??
Data payload body should be applicable for request methods 'GET'
reactjs - How to send body data and headers with axios get request? - Stack Overflow
axios get request with body and header - javascript
Videos
How about using direct axios API?
axios({
method: 'post',
url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
headers: {},
data: {
foo: 'bar', // This is the body part
}
});
Source: axios api
You can use postman to generate code. Look at this image. Follow step1 and step 2.

If your endpoint just accepts data that have been sent with Body (in postman), You should send FormData.
var formdata = new FormData();
//add three variable to form
formdata.append("imdbid", "1234");
formdata.append("token", "d48a3c54948b4c4edd9207151ff1c7a3");
formdata.append("rate", "4");
let res = await axios.post("/api/save_rate", formdata);
Hey all! I've been working on the frontend of a project and the backend dev gave me a GET endpoint with a json body. Axios and fetch don't support data or bodies with get requests. Is there a way I can work around this without him changing the backend?
It is NOT possible to pass data inside a body on a GET request.
GET request only allow you to pass values via the Params or Headers.
Backend E. g.:
const data = req.query.data;
Frontend E. g.:
const headers = {
'Authorization': `Bearer ${token}`
};
const params = {
data: 'Some Text'
};
const data = await axios.get(
"http://localhost:5000/api/data",
{ headers, params }
);
If you want to pass data in the body, you could also change the method to POST -- if there is no other way around.
const DELIVARAY = process.env.DELIVARAY;
const ekshop_delivary_api_key = process.env.DELIVARAY_API_KEY;
const ekshop_delivary_api_secret = process.env.DELIVARAY_API_SECRET;
export const axios_parcel_track = (method: any, data: string, url: string) => {
const options = {
method: method,
headers: {
"API-SECRET": ekshop_delivary_api_secret,
"API-KEY": ekshop_delivary_api_key,
},
data: { parcel_no: data }, // parcel_no is my db field
url: DELIVARAY + url,
};
return { ...options };
};
here method = "get" ; data ="string" ; url="string/string" ;
passed through with extra data. here data goes through body .as like post request.
In general there is no point in a body for GET requests, so axios does not support it.
If you read the axios config documentation, you will find
//
datais the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
You can read more at HTTP GET with request body for the reasons.
If you want to send data in a GET request use the params property
//
paramsare the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
There is no field related to body in get method in axios you can transfer data by get the data in query in URL like this:
const searchByDate = async ({ date1, date2 }) => {
const data = { date1: date1, date2: date2 }
const tokenApp = window.localStorage.getItem('token');
const { data: res } = await axios.get(`${baseUrl}/search?data=${JSON.stringify(data)}`, {
headers: { Authorization: `${tokenApp}` },
});
return res;
};
in backend to convert the data from string to original data types just wrap the data in
JSON.parse(data)
Not all clients and servers support body in GET request. In this case, the browser can't send body in GET request (axios supports sending body in GET request).
As a workaround, you can change the method from 'GET' to 'POST'
Like so:
axios.request({
method: 'POST',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
data: {
next_swastik: 'lets add something here'
},
})
and change your api to expect a post
app.post('/next/api', verifyToken, function(req, res) {
console.log(req.body);
});
or
Change the data property to params
axios.request({
method: 'GET',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
params: {
next_swastik: 'lets add something here'
},
})
and change the api to log out the params
app.get('/next/api', verifyToken, function(req, res) {
console.log(req.params);
});
and like @MaieonBrix said, make sure that your headers contain the content type that you are sending.
It looks like you only have two points left to make it work :
one : the http method should be set to
POSTinstead ofGETsince you want to send something.two : you can then add the http header (like what you did with the authorization header)
Content-Type: 'application/json`
On the back-end don't forget to use some kind of body parser utility package like this one : body-parser and set it up with your app.
I suppose your server is using express, here is how you will do it with express :
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json();
app.use(jsonParser); // use it globally
app.get('your_route', jsonParser, otherMiddleware, (req, res) => ...); // use it for specific routes
/* ... rest of your code */