可能未处理的承诺拒绝/错误:请求失败,状态码为 400
Posted
技术标签:
【中文标题】可能未处理的承诺拒绝/错误:请求失败,状态码为 400【英文标题】:Possible Unhandled Promise Rejection / Error: Request failed with status code 400 【发布时间】:2018-12-21 14:57:52 【问题描述】:我知道对此有一些答案,我已全部阅读。但他们都没有帮助。 所以这是我的错误信息:
这是我的行动:
export function registerUser(data)
const request = axios(
method: "POST",
url: `$REGISTER$API_KEY`,
data:
email: data.email,
password: data.password,
,
headers:
"Content-Type":"application/json"
).then(response => response.data)
return
type: "REGISTER_USER",
payload: request,
谢谢!
【问题讨论】:
【参考方案1】:尝试获取库以进行 API 调用。
function registerUser(data)
return fetch(url,
method: 'POST',
body: JSON.stringify(data),
headers:
'Content-Type': 'application/json'
)
.then(res => res.json())
.then((apiResponse)=>
console.log("api response", apiResponse)
return
type: "REGISTER_USER",
api_response: apiResponse.data
)
.catch(function (error)
return
type: "REGISTER_USER",
api_response: success: false
)
调用上述函数
let data =
email: "youremail@gmail.com,
password:"yourpassword"
registerUser(data).then((response)=>
console.log(response)
)
【讨论】:
【参考方案2】:记录错误并成功然后检查:
export function registerUser(data)
const request = axios(
method: "POST",
url: `$REGISTER$API_KEY`,
data:
email: data.email,
password: data.password,
,
headers:
"Content-Type":"application/json"
)
.then(function (response)
// handle success
console.log(response);
)
.catch(function (error)
// handle error
console.log(error);
)
【讨论】:
我将数据记录到控制台并且我拥有它。 它不再给我警告,但仍然无法正常工作。【参考方案3】:你应该使用catch
处理程序来调用一个带有promise的api,因为当api失败并且你必须处理错误时你不这样做。
export function registerUser(data)
return axios(
method: 'post',
url: `$REGISTER$API_KEY`,
data:
email: data.email,
password: data.password,
,
headers:
'Content-Type': 'application/json'
)
.then(function (response)
//handle success
return
type: "REGISTER_USER",
payload: response.data,
)
.catch(function (err)
//handle error
return
type: "REGISTER_USER_FAILED",
payload: null
);
这样调用函数
const data =
email: 'asd@asd.asd',
password: 123
registerUser(data).then((response)=>
console.log(response)
)
【讨论】:
【参考方案4】:export function registerUser(data)
return axios(
method: "POST",
url: `$REGISTER$API_KEY`,
data:
email: data.email,
password: data.password,
,
headers:
"Content-Type":"application/json"
).then((api_response)=>
return
type: "REGISTER_USER",
api_response: api_response.data
).catch(function (error)
return
type: "REGISTER_USER",
api_response: success: false
)
//Invoking the above function
let data =
email: "youremail@gmail.com,
password:" password"
registerUser(data).then((response)=>
console.log(response)
)
【讨论】:
它删除了警告,但我仍然没有得到数据。 您从 API 响应中获得的数据。是空的吗? 我得到 newUser 等于成功:false 从 API 你得到响应但该值没有返回给函数 registerUser 是这样的。 我想是的。这就像我这样做的第二天,所以我对这一切有点困惑。以上是关于可能未处理的承诺拒绝/错误:请求失败,状态码为 400的主要内容,如果未能解决你的问题,请参考以下文章
405 - 未捕获(承诺中)错误:请求失败,状态码为 405