Axios POST request fails with error status code 500: Internal Server error
Feb 2021. Wasted 2 hours on this. Not much help on this famous library on internet.
Solution:
- In the catch block, the
error
which will always be500 internal server error
- so, use
error.response.data
instead oferror
.
Code:
try { let result = await axios.post( // any call like get "http://localhost:3001/user", // your URL { // data if post, put some: "data", } ); console.log(result.response.data);} catch (error) { console.error(error.response.data); // NOTE - use "error.response.data` (not "error")}
Update:
I ended up writing a common function for handing error:
File: common.app.js
export const errorUtils = { getError: (error) => { let e = error; if (error.response) { e = error.response.data; // data, status, headers if (error.response.data && error.response.data.error) { e = error.response.data.error; // my app specific keys override } } else if (error.message) { e = error.message; } else { e = "Unknown error occured"; } return e; },};
So I also got stuck in the same problem and the solution that I found was something like this :
let data = JSON.stringify({ username: this.state.username, password: password});const response = axios.post(url,data,{headers:{"Content-Type" : "application/json"}});
This solution worked for me.
Apparently Axios didn't take kindly to the raw JSON object
{username: this.state.username, password: password}
but passing the data into a FormData object seemed to work just fine!