使用 axioson 400 和 401 状态代码检索响应错误

Per*_*elo 2 javascript reactjs axios

I\xc2\xb4m 尝试使用 axios 进行身份验证,但何时出现错误 400 或 401,在电子邮件和密码丢失或错误的情况下,我无法从 API 获取响应消息,控制台记录 axios 错误仅向我显示以下内容:

\n
\n

错误=>错误:请求失败,状态代码400\nat createError(1.chunk.js:104463)\ nat解决(1.chunk.js:104697)\ nat XMLHttpRequest.handleLoad(1.chunk.js:103940)

\n
\n

不知道如何获得正确的响应,如下所示:\n{"errors":[{"message":"请提供电子邮件和密码。"}]}

\n

这是我的代码

\n
(...)\n\naxios.post('some api for authentication',\n        {\n            email: formData.email,\n            password: formData.password,\n            remember: formData.remember\n        })\n        .then(response => {\n          token = response.data.session.user\n          console.log('response =>', token)\n        })\n        .catch((error) => {\n          token = null\n          console.log('error =>', error)\n        })\n\n(...)\n
Run Code Online (Sandbox Code Playgroud)\n

谢谢

\n

Ale*_*sky 7

根据 axios处理错误,底层错误数据message应在以下位置提供error.response.data

.catch((error) => {
  token = null
  console.log('error =>', error.response.data)
});
Run Code Online (Sandbox Code Playgroud)

您可能想要使用该示例并处理可能发生的不同类型的错误:

.catch(function (error) {
  if (error.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    console.log(error.response.data);
    console.log(error.response.status);
    console.log(error.response.headers);
  } else if (error.request) {
    // The request was made but no response was received
    // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
    // http.ClientRequest in node.js
    console.log(error.request);
  } else {
    // Something happened in setting up the request that triggered an Error
    console.log('Error', error.message);
  }
    console.log(error.config);
});
Run Code Online (Sandbox Code Playgroud)

希望这有帮助!