[Vuejs]-Use axios in Vue Router Navigation Guard

0👍

this.$http will not work because the this pointer in routes.js is different from the this pointer in a view component. Try this in routes.js

console.log(this)

And then try the same thing in a Vue component like App.vue. You’ll see the this in the routes.js refers to the router and not the Vue.prototype.

I would suggest modifying your axios.js like this, adding an instance variable and exporting it.

import Vue from 'vue';
import axios from 'axios';

// noinspection JSIncompatibleTypesComparison
const isDevelopmentMode = process.env.NODE_ENV === 'development';

// base URL for backend access
const backendUrl = (isDevelopmentMode)
  ? 'http://localhost:8081/'
  : '/backend/';

// register axios as HTTP client
const instance = axios.create({
  baseURL: backendUrl,
  withCredentials: isDevelopmentMode,
});
Vue.prototype.$http = instance;

export default instance // we need to export this

then import the instance variable into routes.js (it will be the same one)

import Vue from 'vue';
import VueRouter from 'vue-router';
import instance from '@/plugins/axios'; // this may be a different path?

Vue.use(VueRouter);

function getSession() {
  const session = instance.get('session/info') // use instance here
    .then((response) => response.data);
  return session;
}

0👍

Import axios.js in router.js. For this propose do follow steps:

  1. export axios object.

axios.js

import axios from 'axios';

let ax= axios.create({
  baseURL: backendUrl,
  withCredentials: isDevelopmentMode,
});
Vue.prototype.$http = ax;
export default ax;
  1. Import axios.js in router.js.

router.js

import Vue from 'vue';
import VueRouter from 'vue-router';
import axios from "./axios.js"

Vue.use(VueRouter);

function getSession() {
  const session = axios.get('session/info')
    .then((response) => response.data);
  return session;
}

Leave a comment