I store the token after a successful login in the vuex repository as follows:
axios.post('/api/auth/doLogin.php', params, axiosConfig)
.then(res => {
console.log(res.data);
this.$store.commit('login', res.data);
})
axiosConfig is the file in which I install baseURL export default { baseURL: 'http://localhost/obiezaca/v2' }
, and params is just the data sent to the backend.
My vuex file is as follows:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
logged: false,
token: ''
},
mutations: {
login: (state, response) => {
state.logged = true;
state.token = response;
console.log('state updated');
console.log('state.logged flag is: '+state.logged);
console.log('state.token: '+state.token);
},
logout: (state) => {
state.logged = false;
state.token = '';
}
}
});
It works correctly, I can re-display some of the content in my SPA based on v-if="this.$store.state.logged"
for a registered user. I can access this.$store.state.logged
from any component in my application.
Now I want to add my token to every request that calls my external API. I created a basic Axios http interceptor that looks like this:
import axios from 'axios';
axios.interceptors.request.use(function(config) {
const token = this.$store.state.token;
if(token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
}, function(err) {
return Promise.reject(err);
});
Now I have 2 problems / questions.
- ,
this.$store.state.logged
this.$store.state.token
, javascript? - / javascript ? , , , angularJS, ,
$httpProvider.interceptors.push('authInterceptorService');
config, , vue, , ?
GMaiolo,
import interceptor from './helpers/httpInterceptor.js';
interceptor();
main.js, :
import axios from 'axios';
import store from '../store/store';
export default function execute() {
axios.interceptors.request.use(function(config) {
const token = this.$store.state.token;
if(token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
}, function(err) {
return Promise.reject(err);
});
}
, (GET), , , , , , , - - , .
backend POST- , :
TypeError: $store ' undefined
-. ? , .
, , , fron :
