在 VueJS 组件混合中使用时,Axios 拦截器无法正常运行

Axios interceptor does not function correctly when used in a VueJS component mixin

我们所有的服务器API资源return作为JSON对象如下:

{
  data: {
    ... Business data from the controller
  }
  meta: {
    ... meta data added by middleware
  }
}

想法是将元数据添加到 json 响应中,可用于更新 vuex 存储数据。效果很好,即使我们正在逐步淘汰它以用 pushe 替换它以更轻松地保持我们的客户端状态最新,我们仍然有来自服务器的包装数据对象 return。

基本上,我们有一个 axios 拦截器来处理响应的元部分,然后只抛出原始数据供任何 vuejs 组件处理。

这就是理论。这就是它的工作原理。

引导 Axios

Axios 被引导到应用程序中,如下所示:

window.axios = require('axios');
Vue.prototype.$http = axios;

注意我们过去用 axios 替换了 Vue 资源。 反正。这基本上是在任何其他代码之前完成的。

下一部分是添加拦截器:

引导拦截器

axios.interceptors.response.use(
  (response) => {
    window.app.$emit('update-meta-data', response.data.meta);
    response.data = response.data.data;
    return response;
  },
  (error) => {
    ... error handling goes here
  }
);

常规组件

在任何正则组件中,我们可以做以下事情:

this.$http.get();

结果是 - 对于我的组件 - 元位被拦截器正确剥离。工作出色。

...但是有一个 mixin

我还有一个包含在组件中的mixin;然而,在这些情况下,拦截器不起作用。

这是混合代码:

module.exports = {
  mounted: function() {
    this.$http.get('/resource').then(
      (response) => {
        ... here I expect to be able to do response.data
        ... but the response.data contains the original json object
        ... including both data and meta properties
      }
    )
  }
}

mixin包含在一个组件中如下:

<script>
  module.exports = {
    mixins:[require('../mixins/repository.js')],
    ...
  }
</script>

mounted 方法从 mixin 移动到实际组件时,它按预期工作。不过我不明白为什么。

我认为这是因为 this.$http 可能是另一个没有拦截器的对象,但事实并非如此,因为当我在拦截器中添加 console.log() devug 打印时,我看到了我的从混音中调用,它确实通过它的逻辑。唯一的区别似乎是 response.data 似乎没有设置为 response.data.原始响应的数据。

我希望这一切都有意义。

感谢您的协助!

好的。 我真的很困惑,但终于找到了我的问题。 从服务器返回的数据并不像我预期的那样,而是嵌套在一个额外的数据对象中。 VueJS / Axios 代码完成了我预期的工作;我只是没想到这个服务器资源会错误地包装它两次。

感谢那些花时间阅读这个问题的人。 祝你有美好的一天!