0

In my vue/cli 4/vuex / vue-resource project I read data from protected area with passport from backend api as in routes/api.php:

Route::group(['middleware' => 'auth:api',  'prefix' => 'adminarea', 'as' => 'adminarea.'], function ($router) {
    ...
    Route::get('dashboard', 'API\Admin\DashboardController@index');

I found how to set access token at vue-resource interceptor for auth headers

and in src/main.js I added method :

Vue.http.interceptors.push((request, next) => {   
/*
  console.log('request::')
  console.log(request)

  console.log('this::')
  console.log(this)

  console.log('Vue::')
  console.log(Vue)

  console.log('Vue.$store::')
  console.log(Vue.$store)

  console.log('Vue.$store.getters.token::')
  console.log(Vue.$store.getters.token)
*/

  request.headers.set('Authorization', 'Bearer XXX key')
  request.headers.set('Accept', 'application/json')
  next()
})

and it works for me if I fill bearer token manually, but I did not find how to read it from store? In my code above I failed to read $store.getters value... Which is the valid way ?

UPDATED BLOCK # 1: If in src/main.js I comment line :

import store from './store'

and add line :

import store from './store.js';

then in console I got error :

 ERROR  Failed to compile with 1 errors                                                                                                                                                                                           12:55:54 PM

This relative module was not found:

* ./store.js in ./src/main.js

But with

import store from './store'

I failed get access to store data

Thanks!

Petro Gromovo
  • 1,755
  • 5
  • 33
  • 91

2 Answers2

1

Try importing your Vuex file instead of trying to access the $store via the Vue instance.

import store from './store.js';

Vue.http.interceptors.push((request, next) => {   
      request.headers.set('Authorization', `Bearer ${store.getters.token}`)
      request.headers.set('Accept', 'application/json')
      next()
})
C.Christensen
  • 386
  • 4
  • 8
0

I found decision in writing token into localStorage on login and

reading this value from ue.http.interceptors.push((request, next) => { 
  let token = localStorage.getItem('token')
  request.headers.set('Authorization', 'Bearer '+token)
  request.headers.set('Accept', 'application/json')
  next()
})

That works for me!

Petro Gromovo
  • 1,755
  • 5
  • 33
  • 91