Put works in Postman but not AXIOS

angelHank picture angelHank · Feb 18, 2018 · Viewed 7.7k times · Source

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

Answer

Andy Gaskell picture Andy Gaskell · Feb 18, 2018

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);
});