Programing

vuex와 함께 axios 인스턴스 사용

c10106 2022. 5. 19. 22:31
반응형

vuex와 함께 axios 인스턴스 사용

나는 레일즈 백엔드로 부에 프런트엔드를 만들고 있다.

프런트엔드에서 Axios를 사용하고 있으며 인증을 위해 다음과 같은 인터셉터를 설정했다.

import axios from 'axios'

const API_URL = 'http://localhost:3000'

const securedAxiosInstance = axios.create({
  baseURL: API_URL,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json'
  }
})

const plainAxiosInstance = axios.create({
  baseURL: API_URL,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json'
  }
})

securedAxiosInstance.interceptors.request.use(config => {
  const method = config.method.toUpperCase()
  if (method !== 'OPTIONS' && method !== 'GET') {
    config.headers = {
      ...config.headers,
      'X-CSRF-TOKEN': localStorage.csrf
    }
  }
  return config
})

securedAxiosInstance.interceptors.response.use(null, error => {
  if (error.response && error.response.config && error.response.status === 401) {
    // If 401 by expired access cookie, we do a refresh request
    return plainAxiosInstance.post('/refresh', {}, { headers: { 'X-CSRF-TOKEN': localStorage.csrf } })
      .then(response => {
        localStorage.csrf = response.data.csrf
        localStorage.signedIn = true
        // After another successfull refresh - repeat original request
        let retryConfig = error.response.config
        retryConfig.headers['X-CSRF-TOKEN'] = localStorage.csrf
        return plainAxiosInstance.request(retryConfig)
      }).catch(error => {
        delete localStorage.csrf
        delete localStorage.signedIn
        // redirect to signin if refresh fails
        location.replace('/')
        return Promise.reject(error)
      })
  } else {
    return Promise.reject(error)
  }
})

export { securedAxiosInstance, plainAxiosInstance }

main.js에서는 다음과 같은 방법으로 그들을 이용할 수 있게 하고 있다.

import VueAxios from 'vue-axios'
import { securedAxiosInstance, plainAxiosInstance } from './axios'
Vue.use(VueAxios, {
  secured: securedAxiosInstance,
  plain: plainAxiosInstance
})
new Vue({
  el: '#app',
  router,
  store,
  securedAxiosInstance,
  plainAxiosInstance,
  render: h => h(App)
})

그리고 구성 요소에서 다음과 같이 성공적으로 사용할 수 있다.

이 달러화secured.gething/president')

문제는 내가 받은 곳에서 그것들을 사용할 수 없다는 것이다: 정의되지 않은 '보안' 속성을 읽을 수 없다."

나는 다른 사람들 중 하나를 위해 준비했다.

import { securedAxiosInstance, plainAxiosInstance } from '../axios'

    const store = new Vuex.Store({
        secured: securedAxiosInstance,
        plain: plainAxiosInstance,
    .....

그것을 하는 올바른 방법은 무엇인가?

사용할 수 있다this._vm현재 애플리케이션의 Vue 인스턴스를 참조하는 스토어 내부.

그래서 당신의 경우:

this._vm.$http.secured.get('/items')

대안으로 당신은 당신의 돌연변이/행동에 대한 페이로드로서 Vue 인스턴스를 통과할 수 있다.

this.$store.commit('myMutation',this)

참조URL: https://stackoverflow.com/questions/59105633/using-axios-instance-with-vuex

반응형