Vue JS에서 로그인 API 토큰 처리
다음 로그인 구성 요소를 사용 중:
var Login = Vue.extend({
template: '#auth',
data: function () {
return {username: '',password: '',errorMessage:''};
},
methods : {
login: function (e) {
var _this = this;
$.ajax({
url: "/vue/api/login",
type: "POST",
async:false,
data:{
username:_this.username,
password: _this.password
},
success: function (data) {
// store the token in global variable ??
router.push({
path: '/employeeList',
});
},
error:function (xhr, status, error) {
_this.errorMessage = xhr.responseText
}
});
}
}
});
로그인 API는 성공적인 인증을 위해 토큰 문자열을 반환한다.글로벌 변수 또는 로컬 스토리지에 저장해야 하는가?사용자가 애플리케이션에 로그인했는지 확인한 후 그에 따라 리디렉션할 수 있는 필터가 있는가?
가장 좋은 방법은 VUEX : vue 상태 관리 시스템을 사용하는 것이다.
vuex store.js 파일에서 다음과 같이 사용자의 상태를 정의할 수 있다.
const store = new Vuex.Store({
state: {
user: {
userName:'',
loggedInStatus: true,
authToken: ''
}
},
mutations: {
addWebToken: function(state, webToken){
state.user.authToken = webToken;
},
removeWebToken: function(state){
state.user.authToken = '';
}
},
actions: {
login: function(context, userInput){
$.ajax({
url: "/vue/api/login",
type: "POST",
async:false,
data:{
username:userInput.username,
password: userInput.password
},
success: function (data) {
// store the token in global variable ??
context.commit('addWebToken', webToken); // pass the webtoken as payload to the mutation
router.push({
path: '/employeeList',
});
},
error:function (xhr, status, error) {
_this.errorMessage = xhr.responseText
}
});
},
logput: function(context){
//your logout functionality
context.commit('removeWebToken');
}
}
})
이제 당신의 컴포넌트 > 메소드 > 로그인 x 당신은 당신의 vuex srore에서 당신이 선언했던 로그인 동작을 다음과 같이 발송할 수 있다.
var Login = Vue.extend({
template: '#auth',
data: function () {
return {username: '',password: '',errorMessage:''};
},
methods : {
login: function () {
//passing the username and password in an object as payload to the login action
this.$store.dispatch('login', {username: this.username, ppassword: password});
},
logout: function(){
this.$store.dispatch('logout');
}
}
});
그렇게 하는 것의 이점:
중앙 집중식 상태에서 해당 상태의 사용자 정보를 관리할 수 있는 경우
아래 나온 것처럼 vuex 유지 상태를 사용하여 로컬 스토어에 상태 또는 쿠키로 저장하면 웹토큰을 포함한 사용자의 상태가 저장되고 페이지 새로 고침 시 상태도 유지된다.즉, 사용자가 로그인하여 페이지를 새로 고칠 때, 상점에서 사용자 상태를 유지하므로 웹토큰에 접속하여 로그인 상태를 유지할 수 있다.
const store = new Store({ // ... plugins: [ createPersistedState({ getState: (key) => Cookies.getJSON(key), setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: true }) }) ] })
vuex-persistedstate 설명서에 따라 원하는 경우 vuex 지속 상태 플러그인을 저장소에 추가하고 jscookies 라이브러리를 사용하여 쿠키 또는 다른 로컬 저장소에 사용자 상태를 저장하십시오.
참조URL: https://stackoverflow.com/questions/43581958/handle-login-api-token-in-vue-js
'IT이야기' 카테고리의 다른 글
반응이 오류인데 왜 약속은 .그러면()으로 들어가는가? - 라라벨 (0) | 2022.04.10 |
---|---|
Vuex가 돌연변이를 인식하지 못함 (0) | 2022.04.10 |
루프 내에서 Vuejs 구성 요소의 가변 매개 변수 액세스 (0) | 2022.04.10 |
반응JS - 요소의 높이 가져오기 (0) | 2022.04.09 |
vue.js 애플리케이션의 상태 업데이트에 사용할 항목(rxJs 대 Vuex) (0) | 2022.04.09 |