VueRouter在beforeEach中发出HTTP请求

时间:2018-06-16 02:16:10

标签: vue.js axios vue-router

我正在尝试在router.beforeEach中发出AXIOS请求。但是,看起来请求是我的下一个目标网址被添加的;如果尝试访问/ client / create,则beforeEach似乎在请求前面加上“ / client / create ”。

而不是' / api / participant / test / {some_id} ',请求被发送到' / client / create / api / participant / {some_id} ”。

我不太清楚为什么会这样。文档表明您可以使用 getPost()方法发出请求:

  beforeRouteEnter (to, from, next) {
    getPost(to.params.id, (err, post) => {
      next(vm => vm.setData(err, post))
    })
  },

然而,似乎getPost()方法无法识别,这可能是因为beforeEach调用(文档未显示这可以与此特定方法一起使用)。

以下是AXIOS请求的代码。

  router.beforeEach((to, from, next) => {
    console.log(to.params.id);
    // Check to see if the cookie exists
    if (document.cookie.match(/^(.*;)?\s*participant_token\s*=\s*[^;]+(.*)?$/)) {
      axios.get('api/participant/test/' + to.params.id)
      .then(function (response) {
          console.log(response.data);
        })
      .catch(function (error) {
        console.log(error);
      });
    }

有关如何避免这种情况的任何想法?我想可以在我设置的每条路线上使用beforeRouteEnter,但这将是一个更优雅的解决方案。

2 个答案:

答案 0 :(得分:2)

应该是

axios.get('/api/participant/test/' + to.params.id)

(在初学者处使用正斜杠字符。)

axios config中set baseURL更合适的方式

例如:

axios.defaults.baseURL = 'your base url';

答案 1 :(得分:1)

首先,Vue.js中没有内置的getPost方法。文档提到它只是为了说明目的。

此外,使用根相对网址而不是您尝试使用的相对网址。

axios.get('/api/participant/test/' + to.params.id)

您正在尝试使用导致问题的相对网址。更通用的方法是在 Axios 全局配置中设置默认基本网址