mary
mary

Reputation: 121

vue-resource not passing token in request headers

I'm new to Vuejs 2, currently using vue-resource to retrieve data from the server. However, I would need a token passed in the request header at the same time in order to retrieve the data from the server.

So the problem is, I am unable to retrieve data because the token is not passed into the request header, using vue-resource.

Here is the method that uses the vue-resource's interceptor (to pass in the token) to intercept the GET request:

test () {
  this.$http.interceptors.push((request) => {
    var accessToken = window.localStorage.getItem('access_token')
    request.headers.set('x-access-token', accessToken)
    return request
  })
  this.$http.get(staffUrl)
   .then(response => {
     console.log(response)
   }, (response) => {
     console.log(response)
   })
}

Documentation for vue-resource, HTTP: https://github.com/pagekit/vue-resource/blob/develop/docs/http.md

When I try to GET the data, i end up with an error 403 (forbidden) and after checking the request headers in the dev tools, I also could not find the token in the request headers.

Please tell me where I went wrong because I'm really new to this so i appreciate any help! Thank you!

Upvotes: 1

Views: 2776

Answers (2)

Spring boots
Spring boots

Reputation: 1

please go through this code

import vueResource from "vue-resource";
import { LocalStorage } from 'quasar'

export default ({
    app,
    router,
    Vue
}) => {
    Vue.use(vueResource);

    const apiHost = "http://192.168.4.205:8091/";

    Vue.http.options.root = apiHost;
    Vue.http.headers.common["content-type"] = "application/json";
    Vue.http.headers.common["Authorization"] = "Bearer " + LocalStorage.get.item("a_t");



    Vue.http.interceptors.push(function(request, next) {
        console.log("interceptors", request);
        next(function(response) {

        });
    });
}

Upvotes: 0

Bert
Bert

Reputation: 82459

Setting interceptors inside the component using $http doesn't work, or at least it doesn't in my testing. If you examine/log this.$http.interceptors right after your push in the test method, you'll note that the interceptor was not added.

If you add the interceptor before you instantiate your Vue, however, the interceptor is added properly and the header will be added to the request.

Vue.http.interceptors.push((request, next) => {
  var accessToken = "xyxyxyx"
  request.headers.set('x-access-token', accessToken)
  next()
})

new Vue({...})

Here is the test code I was using.

Also note, if you are using a version prior to 1.4, you should always call the next method that is passed to the interceptor. This does not appear to be necessary post version 1.4.

Upvotes: 4

Related Questions