13

How can I use a interceptor in vue.js? So before every request/response it should first go to the interceptor. I already searched a lot but can't find a good documentation about that.

I would like to use JWTAuth like this:

(function (define) {
  'use strict'

  define(function (require) {

    var interceptor

    interceptor = require('rest/interceptor')

    /**
     * Authenticates the request using JWT Authentication
     *
     * @param {Client} [client] client to wrap
     * @param {Object} config
     *
     * @returns {Client}
     */
    return interceptor({
      request: function (request, config) {
        var token, headers

        token = localStorage.getItem('jwt-token')
        headers = request.headers || (request.headers = {})

        if (token !== null && token !== 'undefined') {
          headers.Authorization = token
        }

        return request
      },
      response: function (response) {
        if (response.status && response.status.code === 401) {
          localStorage.removeItem('jwt-token')
        }
        if (response.headers && response.headers.Authorization) {
          localStorage.setItem('jwt-token', response.headers.Authorization)
        }
        if (response.entity && response.entity.token && response.entity.token.length > 10) {
          localStorage.setItem('jwt-token', 'Bearer ' + response.entity.token)
        }
        return response
      }
    })

  })

}(
  typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require) }
  // Boilerplate for AMD and Node
))

But I don't know how to intercept before every request/response. (I use Laravel 5.2).

Jamie
  • 10,302
  • 32
  • 103
  • 186

2 Answers2

24

example for global config:

Vue.http.interceptors.push({

  request: function (request){
    request.headers['Authorization'] = auth.getAuthHeader()
    return request
  },

  response: function (response) {
    //console.log('status: ' + response.data)
    return response;
  }

});

request is for outcoming traffic and response if for incoming messages

local config in vue component is also possible.

EDIT - since sytax have changed now it should look like this:

Vue.http.interceptors.push((request, next)  => {
  request.headers['Authorization'] = auth.getAuthHeader()
  next((response) => {
    if(response.status == 401 ) {
      auth.logout();
      router.go('/login?unauthorized=1');
    }
  });
});
lukpep
  • 1,559
  • 1
  • 11
  • 18
  • 6
    worth noting that this answer is a little outdated, the syntax is now slightly different. As Linus noted in his answer, check the docs: https://github.com/pagekit/vue-resource/blob/master/docs/http.md#interceptors – Stephan Jan 26 '17 at 10:24
  • what if I add `vue.http.intercepters` into multiple files ?? then code goes into each file before http call ? – Pardeep Jain Jan 15 '18 at 10:11
4

Vue itself has no AJAX functionality. Are you talking about the plugin vue-resource, or do you use some other library for requests?

vue-resource supports has intereceptors: https://github.com/vuejs/vue-resource/blob/master/docs/http.md (scroll down to the last section)

Linus Borg
  • 23,622
  • 7
  • 63
  • 50
  • 1
    you can use links to section (https://github.com/vuejs/vue-resource/blob/master/docs/http.md#interceptors) instead of scrolling – Ivan Borshchov Sep 18 '16 at 19:29