2017-10-05 7 views
0

프런트 엔드에는 vue/webpack을 사용하고 백엔드에는 node.js/express를 사용하여 웹 응용 프로그램을 구축하고 있습니다. node.js 백엔드는 프런트 엔드에서 로그인, 로그 아웃 및 기타 CRUD와 유사한 작업에 사용되는 REST API를 노출합니다.vue 라우터 및 서버 제공 JWT 토큰을 통한 사용자 인증을 관리하는 방법은 무엇입니까?

서버 측에서는 로그인 REST API가 JWT 토큰을 설정하고 vue 응용 프로그램 홈 경로로 리디렉션합니다. 프런트 엔드 쪽에서는 vue 구성 요소 액세스 (집 포함)가 vue 라우터의 beforeEach 메서드에 의해 보호됩니다 (here의 샘플을 기반으로 함).

제 질문은 내 vue 응용 프로그램 내에서 내 응답 메시지의 HTTP 헤더에서 로그인 REST API로 설정 한 JWT 토큰에 액세스하여 내 vuex 저장소에 저장하여 내 vue 구성 요소가 사용할 수 있도록하는 방법입니다. 그것?

도움 주셔서 감사합니다. PS : 나는 Node.js를 8.5, 뷰 2.4.4, 뷰 라우터 2.7, Vuex 2.4.1

답변

0

사용 Axios Interceptors 사용하고 있습니다 :

import { defaults, get } from 'lodash' 
import axios from 'axios' 
import store from 'vuex-store' 
import def from './default' 

export const connection = (options = {}) => { 
    def.headers = { Authorization: store.getters.auth.getToken() } 
    const instance = axios.create(defaults(def, options)) 

    instance.interceptors.response.use(function (response) { 
    const newtoken = get(response, 'headers.authorization') 
    if (newtoken) store.dispatch('setToken', newtoken) 
    console.log(response.data) 
    return response 
    }, function (error) { 
    switch (error.response.status) { 
     case 401: 
     store.dispatch('logoff') 
     break 
     default: 
     console.log(error.response) 
    } 
    return Promise.reject(error) 
    }) 

    return instance 
}