반응형
NuxtJS에서 인증된 Axios 글로벌 구성 - VueJs
나는 NuxtJS - VueJS에서 인증된 것으로 Axios를 전세계적으로 구성할 수 있는 방법을 찾는다. (나는 주로 NUXTJS를 사용한다.)
내가 필요한 모든 것은: 만약 사용자가 로그인해서 $store에 토큰을 가지고 있다면, 악시오는 이 토큰을 얻을 것이다. 사용자가 익명인 경우 axios가 이 토큰을 가져오지 않음
~/플러그인/포도스
import axios from 'axios'
import AuthenticationStore from '~/store'
var api = axios.create({
baseURL: 'http://localhost:8000/api/v1/',
'headers': {'Authorization': 'JWT ' + AuthenticationStore.state.token}
})
api.interceptors.request.use(function (config) {
config.headers = {
'Authorization': AuthenticationStore.state.token ? 'JWT ' + AuthenticationStore.state.token : ''
}
return config
}, function (error) {
// Do something with request error
return Promise.reject(error)
})
export default api
~/store/index.js
const AuthenticationStore = () => {
return new Vuex.Store({
state: {
token: null
},
mutations: {
SET_TOKEN: function (state, token) {
state.token = token
instance.defaults.headers = { Authorization: 'Bearer ' + token }
}
},
actions: {
....
}
})
}
export default AuthenticationStore
오류:[nuxt] Error while initializing app TypeError: Cannot read property 'token' of undefined
나는 대신 창조하지 않고 요청을 할 때 보다 유연하고 토큰을 얻는 인터셉터를 사용할 것을 제안하고 싶다.토큰이 설정되지 않은 문제를 방지하려면 이와 같은 방법을 시도해 보십시오.
// ~/plugins/axios
import axios from 'axios'
import AuthenticationStore from '~/store'
var api = axios.create({
baseURL: 'http://localhost:8000/api/v1/',
'headers': {'Authorization': 'JWT ' + AuthenticationStore.state.token}
})
api.interceptors.request.use(function (config) {
config.headers = {
'Authorization': AuthenticationStore.state.token ? 'Bearer ' + AuthenticationStore.state.token : ''
}
return config
}, function (error) {
// Do something with request error
return Promise.reject(error)
})
export default api
auth 헤더가 필요 없는 경우, 인터셉터의 구걸에 따라 추가해야 한다.
스토어 문제:스토어 인스턴스를 내보내야 할 때 함수를 내보내는 중이므로 잘못된 경우:
const AuthenticationStore = () => {
다음과 같이 인스턴스를 내보내십시오.
const AuthenticationStore = new Vuex.Store({ ...
더 나은 이해를 얻으려면 https://vuex.vuejs.org/guide/을 방문하십시오.네가 충분히 이해하지 못하는 것도 나쁘지 않아!JS에서의 모듈/인스턴스/수출은 완전히 이해하기가 쉽지 않다.그냥 좀 더 배워봐.행운을 빈다.
반응형
'programing' 카테고리의 다른 글
Vue의 v-on 지시어에 여러 이벤트 바인딩 (0) | 2022.05.10 |
---|---|
VueJS - v-bind:스타일 + 호버 (0) | 2022.05.10 |
JUnit4에서 특정 순서대로 테스트 방법을 실행하는 방법? (0) | 2022.05.10 |
Vuejs 2.3 - 동기화 및 요소 Ui 대화상자 (0) | 2022.05.10 |
Eclipse for Java 텍스트 편집기에서 글꼴 크기를 변경하는 방법 (0) | 2022.05.10 |