【问题标题】:Axios catch not working with Laravel API but only for errorsAxios 捕获不适用于 Laravel API,但仅用于错误
【发布时间】:2021-10-20 10:33:34
【问题描述】:

我有一个 React 应用程序设置为使用 Santum 调用 Laravel API,但我遇到了返回错误代码的 API 调用问题。然而,成功的结果工作正常。

例如,如果我运行:

axios.get('http://website.test/api/collections')
.then(function (response) {
    console.log(JSON.stringify(response));
})
.catch(function (error) {
    console.log(JSON.stringify(error));
});

然后我按预期返回一个集合列表,一切都很好。

但是,如果我尝试一些应该出错的东西(比如 404):

axios.get('http://website.test/api/doesnotexist')
.then(function (response) {
    console.log(JSON.stringify(response));
})
.catch(function (error) {
    console.log(JSON.stringify(error));
});

它总是调用'then'函数而不是catch,但内容是:

Error: Request failed with status code 404
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

带有 422 响应的验证错误会发生非常相似的情况。

我已经按照文档设置了 Sanctum,并且 axios 使用 withCredentials。正如我所说,来自 API 的 200/201 响应工作正常,但我就是不明白为什么错误不能?控制台中也没有显示 CORS 错误。

【问题讨论】:

    标签: laravel axios


    【解决方案1】:

    好吧,答案是我自己的愚蠢。

    我在另一个文件中有一个 axios 拦截器,我没有检查就从另一个项目中复制了它,它会将除 401 以外的所有错误标记为正常。

    不确定这里的礼仪是什么,但如果应该删除它就可以了,否则我很乐意留下它,以防它帮助像我这样粗心的其他人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      • 2021-09-08
      • 2020-03-16
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      相关资源
      最近更新 更多