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

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


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


不知道如何获得正确的回复,如下:{“errors”:[{“message”:“请提供电子邮件和密码。”}]}


这是我的代码


(...)


axios.post('some api for authentication',

        {

            email: formData.email,

            password: formData.password,

            remember: formData.remember

        })

        .then(response => {

          token = response.data.session.user

          console.log('response =>', token)

        })

        .catch((error) => {

          token = null

          console.log('error =>', error)

        })


(...)


杨魅力
浏览 162回答 1
1回答

万千封印

根据 axios处理错误,底层错误数据message应在以下位置提供error.response.data:.catch((error) => {  token = null  console.log('error =>', error.response.data)});您可能想要使用该示例并处理可能发生的不同类型的错误:.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);});希望这有帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript