【问题标题】:VueRouter make HTTP request within beforeEachVueRouter 在 beforeEach 内发出 HTTP 请求
【发布时间】:2018-11-25 19:43:57
【问题描述】:

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

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

【问题讨论】:

    标签: vue.js axios vue-router


    【解决方案1】:

    应该是

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

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

    在 axios 配置中set baseURL 的更正确方法

    例如:

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

    【讨论】:

    • 因为错过了那个而感到很傻——在我的应用程序的其他任何地方,我在 url 之前都使用了“/”。
    【解决方案2】:

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

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

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

    您正在尝试使用对您造成问题的相对 URL。更通用的方法是在 Axios 全局配置中设置默认的 base URL

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 2014-08-15
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多