VueRouter 在 beforeEach 中发出 HTTP 请求

VueRouter make HTTP request within beforeEach

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

而不是'/api/participant/test/{some_id}'请求被发送到'/client/create/ api/参与者/{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,但这将是一个更优雅的解决方案。

应该是

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

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

在 axios 配置

set baseURL 更正确的方法

例如:

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

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

此外,使用 root 相对 URL 而不是您尝试使用的相对 URL。

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

您正在尝试使用相对 URL,这给您带来了问题。更通用的方法是在 Axios 全局配置中设置默认 base URL