pconn12
pconn12

Reputation: 181

Axios 400 Bad request in React

I have read every issue on here regarding Axios 400 bad request and I can't find a solution. I have a function I am calling during useEffect that firstly gets data from my API and then later based on other factors may need to POST back to the API.

the GET call works perfect, but the POST call keeps failing.

const home = match.homeTeam.team_name
const homeScore = null
const away = match.awayTeam.team_name
const awayScore = null
const gameID = match.fixture_id
const result = ""
const points = null
const teamName = userInfo.state.teamName
const date = match.event_date
const status = match.statusShort
const realHomeScore = null
const realAwayScore = null
const homeLogo = match.homeTeam.logo
const awayLogo = match.awayTeam.logo
axios.post('/picks/add/', { home, homeScore, away, awayScore, gameID, result, points, teamName, date, status, realHomeScore, realAwayScore, homeLogo, awayLogo })
            .then((result) => {
                console.log(result.data);
            })
            .catch((error) => {
                console.log(error);
            })

I have checked my payload in Network and it's sending exactly what I want.

I get the following error message in my Catch:

Error: Request failed with status code 400
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:60)

The route works fine in Postman, and the POSTS I make in there match up exactly with the payload in my requests on the web. But for some reason they fail.

Does this have to do with making two requests to the same API within the same function? My first request is in an Await so it runs and finishes before the rest of the function goes.

Any input would be greatly appreciated, thanks!

Upvotes: 12

Views: 86014

Answers (1)

willieswanjala
willieswanjala

Reputation: 678

You could console.log(error.response) in your catch block to get a more human-readable object.

Edit: axios errors come in three types: message, request and response. To make sure you are handling all possible errors, you could use a conditional block:

if (error.response){

//do something

}else if(error.request){

//do something else

}else if(error.message){

//do something other than the other two

}

Upvotes: 42

Related Questions