import API_LOGIN from config API import Axios from axios export defaul

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
import { API_LOGIN } from '../config/API';
import Axios from 'axios';
export default {
state: {
token: localStorage.getItem('access_token') || null,
id: localStorage.getItem('id') || null,
name: localStorage.getItem('name') || null,
email: localStorage.getItem('email') || null,
password: localStorage.getItem('password') || null,
// headers: []
},
getters: {
// loggedIn сравнивает токен
loggedIn: state => state.token !== null,
getData: state => state.data,
id: state => state.id,
name: state => state.name
// headers: state => state.
},
mutations: {
SET_USER(state, data) {
state.token = data.token;
state.id = data.id;
state.name = data.name;
state.email = data.email;
state.password = data.password;
},
},
actions: {
// Логинимся и записываем токен
SIGNIN(context, payload) {
context.commit('SET_PROCCESSING', true)
return new Promise ((resolve, reject) => {
Axios.post(API_LOGIN, {
// получили данный от пользователя в signin
email: payload.email,
password: payload.password,
})
.then(response => {
// получили access_token
const token = response.data.success.token;
const id = response.data.success.id;
const name = response.data.success.name;
console.log(response);
// Axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
// Axios.defaults.headers.common['Accept'] = 'application/json';
localStorage.setItem('access_token', token);
localStorage.setItem('id', id);
localStorage.setItem('name', name);
context.commit('SET_USER', {
token: token,
id: id,
name: name
});
context.commit('SET_PROCCESSING', false)
resolve(response)
})
.catch(error => {
context.commit("SET_PROCCESSING", false);
context.commit("SET_ERROR", error.message);
reject(error)
})
})
},
// Регистрация
SIGNUP({ commit }, payload) {
commit("SET_PROCCESSING", true);
Axios.post(API_LOGIN, {
// получили данный от пользователя в signin
email: payload.email,
password: payload.password,
})
.then(user => {
commit("SET_USER", {
email: email,
password: password
});
commit("SET_PROCCESSING", false);
})
.catch(function(error) {
commit("SET_PROCCESSING", false);
commit("SET_ERROR", error.message);
});
},
// Удаляем token поле выхода
DESTROY_TOKEN(context) {
console.log(1234);
Axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token;
if(context.getters.loggedIn) {
// удаляем токен
localStorage.removeItem('access_token');
context.commit('DESTROY_TOKEN');
console.log('token удален', DESTROY_TOKEN);
}
},
},
}