javascript - axios错误处理的对象error.response 是空

查看:921
本文介绍了javascript - axios错误处理的对象error.response 是空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

_this.$http.post(`/company/${id}/out`, {
  access_token: _this.access_token,
}).then((res) => {
  let info = res;
}).catch((err) => {
  console.log(err.response);
  // err.response 是 undefined
})
},

我想在 403 或者 401 的时候去处理这个错误,但是拿不到这个状态码。但是官网上就是这么用的。

axios.get('/user/12345')
  .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);
  });

我的axios 的版本是 ^0.16.1。

解决方案

注意到里面有 response to preflight 字样。 请注意使用post的时候,浏览器是不是先发了一个OPTIONS的请求。
出现这种错误可能你服务器没有处理OPTIONS的请求。
贴出我的代码:

// 跨域设置
router.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin',  'http://localhost:8080')
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept,withCredentials')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    res.header("Access-Control-Max-Age", "1728000")
    //允许凭证,解决session跨域丢失问题
    res.header('Access-Control-Allow-Credentials', 'true')
    // res.header('Content-Type', 'application/json;charset=utf-8')
    console.log('SESSION Name', req.session.name)
    if (req.method == 'OPTIONS') {
        res.end('OK')
    }
    else {
        next()
    }
})

这篇关于javascript - axios错误处理的对象error.response 是空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆