简体   繁体   English

如何使用javascript / axios从服务器访问错误响应

[英]How to access error response from server using javascript / axios

I am using axios to post form data to Laravel. 我正在使用axios将表单数据发布到Laravel。

Currently I am able to access the response if successful, however I'm having trouble accessing the error response. 目前,如果成功,我可以访问响应,但是访问错误响应时遇到问题。 In dev tools, I can see my network > response has the following: 在开发工具中,我可以看到我的网络 > 响应具有以下内容:

{"success":false,"data":{"message":"Token mismatch","refresh":true}}

I'm trying to access refresh to do a boolean comparison, so if its true the page will reload. 我正在尝试访问refresh进行布尔比较,因此,如果它为true,则将重新加载页面。 How do I access this? 我该如何访问?

I've tried the following: 我尝试了以下方法:

console.log(error.response);
console.log(error.response.data);
console.log(error.response.data.message);
console.log(error.data);
console.log(error);

Which log as the following respectively: 该日志分别如下:

[object Object]
[object Object]
undefined
undefined
Error: Request failed with status code 419

It seems that your server response contains data key. 您的服务器响应似乎包含data密钥。 Axios also uses this key to in order to separate application data from HTTP protocol status and headers . Axios还使用此密钥来将应用程序数据与HTTP协议statusheaders分开。

Assuming that you want to get message from the error response (that is "Token mismatch") try to access it using the following path: 假设您要从错误响应中获取message (即“令牌不匹配”),请尝试使用以下路径进行访问:

error.response.data.data.message

Add

{{csrf_field()}} 

With your post request to avoid 419 error 与您的帖子请求一起避免419错误

As per the [ https://github.com/axios/axios#handling-errors] documentation the error is available in the response. 根据[ https://github.com/axios/axios#handling-errors]文档,该错误在响应中可用。 use try catch instead 使用try catch代替

try {
    apiRes = axios.get('https://www.apponative.con');
  } catch (err) {
    console.error("Error response:");
    console.error(err.response.data);    // ***
    console.error(err.response.status);  // ***
    console.error(err.response.headers); // ***
  } finally {
    console.log(apiRes);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM