简体   繁体   中英

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

It is required to make 2 different requests for one page using middleware.
The first thing that comes to mind is something like this:
(I understand that 2 returns look pretty dumb.)

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:

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

We can observe on the screenshot - only the first request is triggered.
( 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
  • 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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