【问题标题】:Execute function after every post request每次发布请求后执行功能
【发布时间】:2019-12-31 14:08:18
【问题描述】:

使用 Axios 有没有办法将函数“挂钩”到每个发布请求?

我在Vue.js 商店中有一个“通知”模块,用于存储 API 响应,因此我需要在每个发布请求 .then 中调用 updateResponse 方法

【问题讨论】:

  • 为什么不为此创建一个 Vue 组件?
  • 我有多个组件,我从中分派一个涉及发布请求的操作,在这些操作之后,我总是必须提交相同的突变来更新存储在 Vuex 存储中的 API 响应。 API 响应随后会显示在组件中。我要做的是:不是在每个 axios.POST 下显式编写“updateResponse”突变调用,而是将其“挂钩”到每个 post 请求一次

标签: javascript vue.js axios


【解决方案1】:

只需使用Axios interceptors

axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

【讨论】:

  • 有没有办法将拦截器仅限于特定的 HTTP 方法? (在我的情况下,除了 GET 方法之外的所有方法)
  • 不,您需要自己实现。 'response' variable 具有 request 键,因此您可以使用它来检测 POST 请求...
【解决方案2】:

你可以在你的 vue.js 应用中添加一个拦截器

因此您可以在每个帖子回复到达.then() 函数之前捕获它们

window.intercepted.$on('response', data => {
        console.log(data); // { status: 404, code: 'Not found', body: null }

        // Display the message.
    });

您可以在 vue-axios-interceptors 包here中找到更多相关信息

【讨论】:

  • 我正在寻找一种无需打包的方法
猜你喜欢
  • 1970-01-01
  • 2021-06-01
  • 1970-01-01
  • 2016-01-05
  • 1970-01-01
  • 2019-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多