问题描述
我有一个Laravel Lumen 7 RESTful API和一个带有Axios的Nuxt JS前端。我的前端对API进行了Axios调用,在我的Lumen项目中,我当然会返回相关的响应和错误代码。但是,看起来这些响应虽然可以在检查网络时看到并在预览/响应选项卡中看到,但无法从Axios的catch()
块中访问。...>
如果将其更改为200
响应,则可以从我的then()
块访问它,但这并不理想。
流明响应
return response()->json(['success' => false,'message' => 'We\'re unable to add this domain right Now,please try again shortly'],500);
JS Axios函数
/*
** Add domain
*/
addDomain () {
// add new domain
this.$axios.post(`${process.env.API_URL}/api/domains/add`,this.domainCreation).then(res => {
console.log(res)
}).catch(err => {
console.log(err) // doesn't display my Object from laravel,instead just the native error string: "Error: Request Failed with status code 500"
})
}
有人可以帮忙吗?
解决方法
尝试此err.response
捕获错误数据在response
内部
this.$axios.post(`${process.env.API_URL}/api/domains/add`,this.domainCreation).then(res => {
console.log(res)
}).catch(err => {
console.log(err.response);
})
参考链接https://github.com/axios/axios#handling-errors
,除了以上答案外,您还应考虑返回正确的响应代码。
5xx
错误代码用于内部服务器错误。您可能正在寻找返回422
不可处理的实体错误。
有关500个状态码的更多信息:https://httpstatuses.com/500
有关422状态代码的更多信息:https://httpstatuses.com/422