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.
How can I add raw data body to an axios request?
axios post request with json data
axios get request with body and header - javascript
Axios Post Request Help! When I use Get request, it works perfectly fine though. Essentially, when I make a post request using axios, there is no data that is being passed through. I tried even setting the data param to Id: "string", and even that didn't pass through as im getting undefined.
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);
By default axios uses Json for posting data so you don't need to stringify your data. The problem could be that you're doing that. Could you try doing the post without it and check if it works? Also you don't need the curly braces to wrap your data unless that's the format of the object in your server. Otherwise could you give me information about how the body of the request looks like so I have more context? You can check that in chrome dev tools using the network tab
You don't need to stringify your payload. Axios will do it for you when it it send a request.
const dt = { data: { value: "gdfg1df2g2121dgfdg" }};
const request = axios.post(url, dt);
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)
Front
import React from 'react'import { useState } from 'react'import Sidebar from './sidebar/Sidebar'import Axios from 'axios'import './gui.css'const sideBar3Dark = {height : '100vh',width : '82.5vw',backgroundColor : '#161818',marginLeft: '17.5vw'}function HomeGui() {const [newAboutUs, setVal] = useState("");const handleSubmit = (e) => {e.preventDefault();/*Axios.get('http://localhost:4000/api/get/aboutUs').then(res => {console.log(res);})*/Axios.post('http://localhost:4000/api/post', { Id: newAboutUs }).then(res => console.log(res)).catch(err => console.log(err));
}return (<div className='homeGui'><form onSubmit={ handleSubmit }><input type="text" value = {newAboutUs} onChange={(e) => {setVal(e.target.value)}}/><button></button></form></div>
)}function Gui() {const [contentStyle, setContentStyle] = useState(sideBar3Dark)return (<><div className='gui'><Sidebar changeStyle={(size) => {setContentStyle(size)}} /><div className='mainGui' style={ contentStyle }><HomeGui/></div></div></>
)}export default Gui
Backend
const express = require('express');const app = express();const bodyParser = require("body-parser");const cors = require('cors');const fs = require('fs');app.use(cors());app.use(bodyParser.urlencoded({ extended: true }));app.get("/api/get/aboutUs", (req, res) => {fs.readFile('../client/src/data/aboutUs.json', 'utf-8', (err, jsonString) => {if (err) {console.log(err);} else {try {const data = JSON.parse(jsonString);console.log(data);res.send(data);} catch(err) {console.log(err);}}});});app.post("/api/post", (req, res) => {console.log(req.body.Id);});app.listen(4000, () => {console.log('PORT 4000 connected');});
Essentially at when I perform console.log(req.body.Id) in app.post(...), it just says undefined in my console, but I do not know why.
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?