简体   繁体   English

如何使用中间件对 1 个页面发出 2 个 Axios 请求?

[英]How to make 2 Axios requests for 1 page with middleware?

It is required to make 2 different requests for one page using middleware.需要使用中间件对一个页面发出 2 个不同的请求。
The first thing that comes to mind is something like this:想到的第一件事是这样的:
(I understand that 2 returns look pretty dumb.) (我知道 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);
        });

  }

}


Next, look at the console in Firebug:接下来看看Firebug中的控制台:

введите сюда описание изображения

We can observe on the screenshot - only the first request is triggered.我们可以在屏幕截图上观察到 - 只有第一个请求被触发。
( console.log('111'); ) ( console.log('111'); )

Question:题:
How to correctly, from the point of view of syntax and design, release a conceived idea?如何从语法和设计的角度正确地发布一个构思?

    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)
    }

Note:笔记:

  • notice the order of R1 and R2 in all , spread and then注意所有的R1和R2的顺序,传播
  • i've predefined the base url of axios in nuxt.config.js you can do that or import axios and use axios.get('fullUrl') instead of this.$axios.get()我已经在nuxt.config.js预定义了 axios 的基本 url 你可以这样做或者import axios并使用axios.get('fullUrl')而不是this.$axios.get()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM