通过拦截器保存到localStorage获取axios响应

时间:2017-10-26 12:20:05

标签: vue.js axios

编辑:没有记录的原因是因为有一个拦截器将auth标头保存到本地存储。我需要继续响应,所以我可以保存用户信息。我把拦截器代码放在底部。

我正在使用Vue2和Rails API设置测试,并且我遇到了使用axios记录响应的包版广告。请求访问API并保存记录,当我查看Chrome时,我可以看到响应消息。

为什么这仍然将响应记录为未定义?

组件方法

methods: {
  submit() {
    const credentials = {
      email: this.credentials.email,
      user_name: this.credentials.user_name,
    };

    axios.patch(UPDATE_URL, credentials)
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error);
      });
    },
  },

来自Chrome网络标签页

的回复
{
  "status":"success",
  "data": {
    "id":1,
    "email":"firstuser@example.com",
    "user_name":"padlsoaa",
    "provider":"email",
    "uid":"firstuser@example.com",
    "image":"https://randomuser.me/api/portraits/women/1.jpg",
    "created_at":"2017-10-21T09:45:27.077Z",
    "updated_at":"2017-10-26T12:00:56.864Z",
    "deleted_at":null
  }
}

编辑拦截器保存在main.js

created() {
    axios.interceptors.request.use((config) => {
      config.headers.client = window.localStorage.getItem('client');
      config.headers['access-token'] = window.localStorage.getItem('access-token');
      config.headers.uid = window.localStorage.getItem('uid');
      config.headers['token-type'] = window.localStorage.getItem('token-type');

      return config;
    });

    axios.interceptors.response.use((response) => {
      if (response.headers.client) {
        localStorage.setItem('access-token', response.headers['access-token']);
        localStorage.setItem('client', response.headers.client);
        localStorage.setItem('uid', response.headers.uid);
        localStorage.setItem('token-type', response.headers['token-type']);
      }
    });
  },

1 个答案:

答案 0 :(得分:0)

愚蠢的错误......你必须在拦截器中返回响应,否则永远不会到达.then((response) => { }

axios.interceptors.response.use((response) => {
  if (response.headers.client) {
    localStorage.setItem('access-token', response.headers['access-token']);
    localStorage.setItem('client', response.headers.client);
    localStorage.setItem('uid', response.headers.uid);
    localStorage.setItem('token-type', response.headers['token-type']);
  }
  return response;
});