Home > Mobile >  Django server unable to get data from react Axios
Django server unable to get data from react Axios

Time:01-09

I'm not getting an error but when I saw the logs of my server it prints an empty object {} whenever I send a request to the sever from my react app using axios. I double checked everything every other request in another components of my app works fine, but only in this particular request the data is not being sent! I have no CORS issue!

My react axios request


  // PrivateAxios instance to send api request
  const axiosPrivate = useAxiosPrivate();
  const handleSearch = async () => {
    const data = JSON.stringify({ from_company: keyWord });
    try {
      const response = await axiosPrivate.get(SEARCH_URL, data);
      console.log(response);
      setRecords(response?.data);
    } catch (err) {
      if (!err?.response) {
        console.log("NO SERVER RESPONSE");
      } else {
        console.log("SOMETHING WRONG");
      }
    }
  };

Server log


{} <-- Prints the request.data as an empty object
"GET /api/find_many/ HTTP/1.1" 200 6276

The django server responses with correct details when I send a request with Postman or Thunder Client. The server also prints the object that were sent with the Postman request. I don't know why the server is unable to get the object or data when I request from my react app.

Request sent from Postman returns


{'from_company': 'Jethmal Paliwal'}  <-- Prints the request.data correctly
"GET /api/find_many/ HTTP/1.1" 200 2284

I have double checked everything, my headers are set correctly, Content-Type: application/json, withCredentials: true, and every other possible settings, Even every request from other components works great, but why this particular request doesn't reach the server?

  • Tried writing the data as an Object in the request funcion itself const response = axiosPrivate.get(SEARCH_URL, { "from_company": "Jethmal Paliwal" }); which doesn't work as well. The same empty object gets printed.

  • Tried JSON.stringify the data, which doesn't work as well.

CodePudding user response:

I believe that axios is omitting the data as it's not per REST standard to submit data in the GET request. HTTP allows that, but people and apparently libraries are not expecting it.

This is the API for axios get method:

axios.get(url[, config])

as you see there is no data in the method signature. And if we look at the POST method:

axios.post(url[, data[, config]])

I suggest if you have data to submit to server that you use a POST method instead.

  • Related