How to use Interceptors in Vue.js With Vue resource
In the last tutorial, we have seen how to make http requests in vuejs using vue-resource, In this tutorial, we are going to learn about interceptors in vue.js.
Interceptors
Interceptors help us to pre or post-processing a request, it means we can modify the requests before it sent to the server or we can modify the responses coming back from the request.
Interceptors are defined globally.
Intercepting a request
We are using vue-resource
http client package for intercepting requests in vuejs.
Example:
import Vue from "vue";
import App from "./App.vue";
import VueResource from 'vue-resource';
// telling vue.js to use this package
Vue.use(VueResource);
Vue.http.interceptors.push(function(request,next){
// modifying request headers
request.headers.set('X-CSRF-TOKEN', 'TOKEN'); request.headers.set('Authorization', 'Bearer TOKEN');
next();
})
new Vue({
render: h => h(App)
}).$mount("#app");
In the above example, we first imported VueResource
and telling vue.js to use this package.
The function inside the push
method runs before every request we sent from our vue app.
Inside this function, we can access the entire request
object so that we can modify the request according to our needs, like in the above example we set Authorization
token to the request headers.
Intercepting a response
import Vue from "vue";
import App from "./App.vue";
import VueResource from 'vue-resource';
// telling vue.js to use this package
Vue.use(VueResource);
Vue.http.interceptors.push(function(request,next){
// modifying request headers
request.headers.set('X-CSRF-TOKEN', 'TOKEN');
request.headers.set('Authorization', 'Bearer TOKEN');
next(function(response){ //logging the response body console.log(response.body) });
})
new Vue({
render: h => h(App)
}).$mount("#app");
Here we defined a function
inside next
method, inside that function we can access the response
object which comes back from the api, like in the above code we are logging the response body.