【问题标题】:How to make 2 Axios requests for 1 page with middleware?如何使用中间件对 1 个页面发出 2 个 Axios 请求?
【发布时间】:2020-06-07 12:43:38
【问题描述】:

需要使用中间件对一个页面发出 2 个不同的请求。
首先想到的是这样的:
(我知道 2 次退货看起来很愚蠢。)

export default function ({$axios, req, store, route}) {

  if(route.name == "language-tracker-tracking") {

      console.log('111');

      return $axios.get("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=get_tracking_data&key_id=" + route.params.tracking.toLowerCase(), {})
          .then(response => {
              store.commit('tracking/setTrackingServerData', response.data.data.tracking_data);
          })
          .catch(function (error) {
              console.log(error);
          });


  }

  if(route.name == "language-tracker-tracking") {

      console.log('222');

      return axios.get("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=get_tracking_status" , {
         })
        .then(response => {
            store.commit('tracking/setTrackingStatus', response.data.data.tracking_status);
        })
        .catch(function (error) {
          console.log(error);
        });

  }

}


接下来,查看 Firebug 中的控制台:

我们可以在截图中观察到——只有第一个请求被触发。
(console.log('111');)

问:
如何从语法和设计的角度正确地发布一个构思好的想法?

【问题讨论】:

  • 或许你可以将axios.allaxios.spread结合使用:stackoverflow.com/a/57066175/687137
  • 我不明白 - 在这种情况下我应该如何使用 3 个不同的“store.commit”?我应该将它用于“传播”身体吗?

标签: javascript vue.js axios nuxt.js


【解决方案1】:
    const R1='/requestAPI';
    const R2='/requestAPI';
    try{
       axios.all([
          this.$axios.get(`${R1}`),
          this.$axios.get(`${R2}`),
        ])
            .then(axios.spread((R1,R2) => {
                store.commit('tracking/setTrackingServerData',R1); //or set  the value to your data
                store.commit('tracking/setTrackingStatus',R2); //or set  the value to your data

            }));
    }catch (e) {
        console.log(e)
    }

注意:

  • 注意 R1 和 R2 在 allspreadthen 中的顺序
  • 我已经在 nuxt.config.js 中预定义了 axios 的基本 url,你可以这样做或 import axios 并使用 axios.get('fullUrl') 而不是 this.$axios.get()

【讨论】:

  • 我写了这个:joxi.ru/EA4dWyzHOnbvwA 但我有一个错误。 joxi.ru/n2YLbPaHZwM7Zm
  • 您应该使用 R1.data.data.tracking_data 而不是 response.data.data.tracking_data 因为您在传播中定义了它的名称 R1,并且与第二个请求相同,使用 R2.data。 data.tracking_status 而不是 response.data.data.tracking_status
  • 尝试:console.log(R1) 和 console.log(R2) 以确保您从 api 获得响应
  • 不,不同的是,尝试在导出默认值之上导入 axios,如下所示: import axios from "axios";并使用 axios 而不是 this.$axios
猜你喜欢
  • 2022-10-08
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 2022-11-02
  • 2018-04-30
相关资源
最近更新 更多