使用Nuxtjs中的另一个Api响应数据调用API

时间:2018-03-21 21:27:34

标签: vuejs2 axios vuex nuxt.js

我正在使用Nuxtjs建立一个网站,我希望当我打开网站的任何页面以使用Axios从服务器获取用户信息时,我想使用这些信息从网站上调用另一个API。
例如:我将从服务器获取用户ID和客户端ID,并在API URL上使用它们,假设我得到User id = 5,Client id = 10 我将调用另一个API并使用这些信息

{{1}}


现在我的问题是在第一个API完成之前的第二个API调用,所以我还没有获得用户信息 能否帮我解决这个问题,请注意我想在所有页面上获取用户信息。因此,如果我在任何页面重新加载页面,我想获得用户信息 所以我从布局调用用户信息API并从其他组件调用其他API。

感谢。

1 个答案:

答案 0 :(得分:1)

首先,您应该使用Nuxt.js正式提供的Axios模块https://github.com/nuxt-community/axios-module。他们使Axios和Nuxt.js之间的集成更容易。

Axios使用promise,因此您可以轻松地链接方法来执行此操作。假设您想从/get/product获取来自http://****/getItems?userid=5&clientid=10之前提及的网址的数据,您可以轻松地这样做

this.$axios.$get('/getItems?userid=5&clientid=10')
  .then(data => {
    // You can use your data received from first request here.
    return this.$axios.$post('/get/product', {
      id: data.id,
      clientId: data.clientId
    })
  })
  .then(data => {
    // You can use your data received from second request here.
    console.log(data)
  })

解释

这部分,

this.$axios.$get('/getItems?userid=5&clientid=10')

axios将从提供的url中获取数据,当收到数据时,我们可以在then()块内使用它,因为它接受回调作为参数。

.then(data => {
  // You can use your data received from first url here.
  ...
})

之后,如果您想使用您的数据,您可以使用您想发送的适当参数轻松返回axios请求。

return this.$axios.$post('/get/product', {
  id: data.id,
  clientId: data.clientId
})

您可以再次使用then()块内第二个axios请求收到的数据。

  .then(data => {
    // You can use your data received from second request here.
    console.log(data)
  })

更新

Oke,基于下面评论部分的澄清。我们可以在第一个操作中返回axios promise,然后在第二个方法中返回第一个操作,

actions: {
  callFirst ({ commit }) {
    return this.$axios.$get('/get/first')
      .then(firstResult => {
        commit('SET_FIRST', firstResult)
        return firstResult
      })
  },
  callSecond ({ dispatch, commit }) {
    return dispatch('callFirst').then(firstResult => {
      return this.$axios.$post(`/get/${firstResult.userId}`)
        .then(secondResult => {
          commit('SET_SECOND', secondResult)
          return secondResult
        })
    })
  }
}

使用这种方式,您只需要将callSecond()动作放在您想要的第二个数据中。而且您也不需要将callFirst()操作放在default.vue上。