Leonardo Wildt
Leonardo Wildt

Reputation: 2599

Check if token still valid before request

I am using an index.js file to make api calls in a vue app. Is there a way to add a catch or a before each call to see if my token is still good and have the user redirected to login if it isnt?

import axios from 'axios'

const client = axios.create({
   baseURL : 'http://myapi.com/api/',
    json: true
})

export default {
    async execute(method, resource, data) {
        const token = localStorage.getItem('token')
        return client({
          method,
          url: resource,
          data,
           crossdomain: true ,
          headers: { "Authorization": `Bearer ${token}` }
        }).then(req => {
          return req.data
        })
      },

      getResponses() {
        return this.execute('get', 'GetResponses')
      },

      getAll(){
        return this.execute('get', 'GetAll')
      },

Upvotes: 0

Views: 1883

Answers (2)

Leonardo Wildt
Leonardo Wildt

Reputation: 2599

If anyone is interested i ended up going with an interceptor as per @thanksd My code index.js file in my api folder now looks like this

import axios from 'axios'
import router from '../router'

const client = axios.create({
   baseURL : 'http://myapi.com/api/',
    json: true
})

client.interceptors.response.use(function (response) {
  return response
}, function (error) {
  if (error.response.status === 401) {
    router.push('/Login')
    console.info('auth token expired')
    localStorage.clear()
    sessionStorage.clear()
  } else if (error.response.status === 403) {
    router.push('/Login')
  } else {
    return Promise.reject(error)
  }
})

export default {
    async execute(method, resource, data) {
        const token = localStorage.getItem('token')
        return client({
          method,
          url: resource,
          data,
           crossdomain: true ,
          headers: { "Authorization": `Bearer ${token}` }
        }).then(req => {
          return req.data
        })
      },

      getResponses() {
        return this.execute('get', 'GetResponses')
      },

      getAll(){
        return this.execute('get', 'GetAll')
      },

Upvotes: 1

thanksd
thanksd

Reputation: 55644

You can use an interceptor, where you can pass a function to be called before each request:

const client = axios.create({ baseURL: 'http://myapi.com/api/', json: true });

client.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');

  if (isTokenGood(token)) {
    return config;
  } else {
    logout();
  }
});

Upvotes: 2

Related Questions