了解对 Rest api 的 http 请求的错误响应

问题描述 投票:0回答:2

这是使用 AXIOS 对 REST API 的简单请求:

  await axios.request({
    url: 'https://gorest.co.in/public/v2/users',
    method: 'POST',
    data: {
      "id":2925,
      "name":"Himani Rana",
      "email":"[email protected]",
      "gender":"female",
      "status":"inactive"})
   .catch(error => {
      console.log(error);
    });
  }

此电子邮件已被占用。因此这会引发异常,因为所有用户都必须拥有唯一的电子邮件。

此代码记录以下错误:

{
"message": "Network Error",
"name": "Error",
"fileName": "https://c.staticblitz.com/d/webcontainer.a330fe2aef0d6950e5edf5ad2e9521381ac64c16.js line 15 > eval",
"lineNumber": 3,
"columnNumber": 8750,
"stack": "e.exports@https://typescript-9ggya9.stackblitz.io/turbo_modules/[email protected]/dist/axios.min.js:3:8750\ne.exports/</g.onerror@https://typescript-9ggya9.stackblitz.io/turbo_modules/[email protected]/dist/axios.min.js:3:7558\n",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Authorization": "Token 1a459dd3d2e13a989f01565f5f1ba32350f8216897bb7fee5493feb210a06"
},
"url": "https://gorest.co.in/public/v2/users",
"method": "post",
"data": "{\"id\":2925,\"name\":\"Himani Rana\",\"email\":\"[email protected]\",\"gender\":\"female\",\"status\":\"inactive\"}"
},
"status": null
}

这很难阅读,当我仔细阅读时,除了显示“网络错误”的消息之外,我没有看到任何可以帮助我识别错误的内容。

现在,使用 POSTMAN 或 THUNDER CLIENT 执行此 http 请求只会显示:

[
  {
    "field": "email",
    "message": "has already been taken"
  }
]

这些 REST 客户端如何正确识别错误,而 AXIOS 却不能?

typescript rest http logging axios
2个回答
0
投票

据我了解,问题出在 axios 库中。

尝试重新安装 axios 或改用 Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)。

P.S: 如今,Fetch API 比 axios 更受青睐。


0
投票
import { AxiosError } from "axios";

catch (error) {
    const err = error as AxiosError<ErrorReponse>
    console.log(err.response?.data?.errors[0]?.message)
}
© www.soinside.com 2019 - 2024. All rights reserved.