boisterouslobster
boisterouslobster

Reputation: 1293

VueRouter make HTTP request within beforeEach

I am attempting to make an AXIOS request within router.beforeEach. However, it looks like the request is being made with my next destination URL being prepended; if trying to access /client/create, the beforeEach appears to prepend '/client/create' to the request.

Instead of '/api/participant/test/{some_id}' the request is being sent to '/client/create/api/participant/{some_id}'.

I'm not quite sure why this is happening. The documentation indicates that you could use a getPost() method to make requests:

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

However it seems the getPost() method is unrecognized, which could be because of the beforeEach call (the documentation does not show that this could be used with this particular method).

Here is the code with the AXIOS request.

  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);
      });
    }

Any ideas on how this can be avoided? I imagine one could use beforeRouteEnter for each of the routes I have set up, but this would be a more elegant solution.

Upvotes: 0

Views: 2980

Answers (2)

Harshal Patil
Harshal Patil

Reputation: 21030

First, there is no built-in getPost method in Vue.js. Documentation has mentioned it just as an illustration purpose.

Also, use root relative URL instead of relative URL that you are trying to use.

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

You are trying to use relative URL which is causing a problem for you. The more generic way would be to set default base URL in Axios global config.

Upvotes: 1

ittus
ittus

Reputation: 22403

It should be

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

(with forward slash character at the beginner).

The more properly way to set baseURL in axios config

For example:

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

Upvotes: 2

Related Questions