无法从 Laravel Lumen API 访问 Axios 中返回的错误响应
Unable to access returned error response in Axios from Laravel Lumen API
我有一个 Laravel Lumen 7 RESTful API 以及带有 Axios 的 Nuxt JS 前端。我的前端对 API 进行 Axios 调用,在我的 Lumen 项目内部,我当然会返回相关的响应和错误代码。但是,看起来这些响应虽然我可以在检查网络时看到它们并且可以在 preview/response 选项卡中看到它们,但我无法从我的 catch()
块中的 Axios 访问它...
如果我将其更改为 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);
})
除上述答案外,您还应考虑return输入正确的响应代码。
5xx
错误代码用于内部服务器错误。您可能正在寻找 return 422
无法处理的实体错误。
关于 500 状态码的更多信息:https://httpstatuses.com/500
关于 422 状态码的更多信息:https://httpstatuses.com/422
我有一个 Laravel Lumen 7 RESTful API 以及带有 Axios 的 Nuxt JS 前端。我的前端对 API 进行 Axios 调用,在我的 Lumen 项目内部,我当然会返回相关的响应和错误代码。但是,看起来这些响应虽然我可以在检查网络时看到它们并且可以在 preview/response 选项卡中看到它们,但我无法从我的 catch()
块中的 Axios 访问它...
如果我将其更改为 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);
})
除上述答案外,您还应考虑return输入正确的响应代码。
5xx
错误代码用于内部服务器错误。您可能正在寻找 return 422
无法处理的实体错误。
关于 500 状态码的更多信息:https://httpstatuses.com/500
关于 422 状态码的更多信息:https://httpstatuses.com/422