【问题标题】:Axios 400 Bad request in ReactAxios 400 React 中的错误请求
【发布时间】:2020-05-24 00:44:04
【问题描述】:

我已阅读此处有关 Axios 400 错误请求的所有问题,但我找不到解决方案。我有一个在 useEffect 期间调用的函数,它首先从我的 API 获取数据,然后根据其他因素可能需要 POST 回 API。

GET 调用完美,但 POST 调用一直失败。

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

我在网络中检查了我的有效负载,它正在发送我想要的内容。

我在 Catch 中收到以下错误消息:

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

该路由在 Postman 中运行良好,并且我在其中创建的 POSTS 与我在网络上的请求中的有效负载完全匹配。但由于某种原因,他们失败了。

这是否与在同一个函数中向同一个 API 发出两个请求有关?我的第一个请求在 Await 中,因此它在函数的其余部分运行之前运行并完成。

任何意见将不胜感激,谢谢!

【问题讨论】:

  • 可能是 CORS 问题?没有确切的错误响应很难说。
  • 只是想一想 - 您的 Postman 请求中是否还有其他标题,您忘记在组件中说明?也许您的服务器需要一些特定的标头?
  • 我比较了这些,唯一不同的是 Postman 中的内容长度是 14,这是参数的数量并且是有道理的,在组件中它就像 108....也许这很正常但是我在标题之间看到的唯一不同之处
  • 其他可能是内容类型可能与实际内容不匹配。例如xxx-form-encoding 需要使用查询字符串,为什么 app/json 需要一个 json 对象。

标签: node.js reactjs express mongoose axios


【解决方案1】:

你可以在你的 catch 块中 console.log(error.response) 来获得一个更易读的对象。

编辑:axios 错误分为三种类型:messagerequestresponse。为确保您处理所有可能的错误,您可以使用条件块:

if (error.response){

//do something

}else if(error.request){

//do something else

}else if(error.message){

//do something other than the other two

}

【讨论】:

  • 呃,现在我知道它是什么了,我猜我的一个输入不正确,这很奇怪,因为它在 Postmam 中工作......但至少我现在知道为什么了!我现在会努力解决这个问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 2021-09-29
  • 2021-01-12
  • 1970-01-01
相关资源
最近更新 更多