Put works in Postman but not AXIOS

12,569

Solution 1

This is happening because Axios serializes JavaScript objects to JSON. To serialize in application/x-www-form-urlencoded format you will need to use one of the techniques described in the Axios documentation.

I think qs is a nice solution for you:

let apiUrl = 'http://localhost:3001/api/teams';
//sends the id and new author/text to our api
axios.put(`${apiUrl}/${id}`, qs.stringify(player)).catch(err => {
  console.log(err);
});

Solution 2

Axios doesn't like posting plain objects.

One way to workaround issue is with FormData:

let formData = new FormData();
formData.append('param1', 'hi');
formData.append('param2', 'hello');

axios({
    method: 'POST',
    url: '/api/some-endpoint/',
    data: data
}).then(response => {
    console.log(response);
});

https://github.com/axios/axios/issues/1195

Share:
12,569
angelHank
Author by

angelHank

Updated on June 14, 2022

Comments

  • angelHank
    angelHank almost 2 years

    This is the weirdest thing in my MERN app. When I do a PUT from Postman to my api it works and updates my api and mongoDB. On the front-end it doesn't update the api even though console logs are showing the correct values and the url is the same? Any help or direction would be appreciated... been playing with it for days now.

    POSTMAN PROOF UPDATES WORK

    enter image description here enter image description here

    The code for my axios is as follows:

    handlePlayerSubmit(id, player) {
        console.log('This is the id: ' + id);
        console.log('This is the player: ' + player);
    
        let apiUrl = 'http://localhost:3001/api/teams';
        //sends the id and new author/text to our api
        axios.put(`${apiUrl}/${id}`, player).catch(err => {
          console.log(err);
        });
    

    }

    So I know it's firing due to the console logs... not sure why its not updating the api?

    Also it's not console.logging an error.

    NETWORK SCREEN SHOT IN DEV TOOLS

    enter image description here

    HEADERS FROM NETWORK TAB:

    enter image description here

    enter image description here

  • angelHank
    angelHank about 6 years
    Added a screen shot of network in devtools still nothing with that qs
  • hshokry
    hshokry about 6 years
    Determine why your server is returning a 304. Compare every header value in postman to the headers in your application.