programing

Axios 기본 헤더를 전체적으로 수정할 때 문제 발생 - Vue

sourcetip 2022. 7. 15. 23:12
반응형

Axios 기본 헤더를 전체적으로 수정할 때 문제 발생 - Vue

in main.js

import axios from 'axios';

axios.defaults.headers.common = {
    'Authorization': 'JWT ' + Vue.auth.getToken()
};

axios.defaults.baseURL = process.env.VUE_APP_BASE_URL; //TODO: append the trailing slash

// Add modified axios instance to Vue prototype so that to be available globally via Vue instance
Vue.prototype.$http = axios;

이 시점까지는 정상적으로 동작하고 있습니다.(토큰을 정상적으로 로그인하여 저장할 수 있습니다.)

이제 컴포넌트의 created() 라이프 훅에서 실행된Ajax 호출을 통해 서버에서 사용자 목록을 가져오는 다른 컴포넌트가 있습니다.내 문제는 내가 접속하려고 할 때this.$http컴포넌트에서는 서버로부터 401 에러 응답이 반환됩니다.Authorizationheader는 요청 헤더에서 사용할 수 없습니다(단, axios.defaults는 이미 설정되어 있습니다).headers.common)

이상한 점은 브라우저의 [Refresh]버튼을 누르면 토큰이 요청 헤더에 올바르게 첨부되어 사용자 목록이 정상적으로 취득된다는 것입니다.****

누가 왜 그런 일이 일어나는지 설명해 줄 수 있나요?

사용자 Axios가 대행 수신기를 요청하여 헤더를 글로벌하게 추가할 수 있습니다.

axios.interceptors.request.use(function (config) {
// Do something before request is sent
  return config;
}, function (error) {
// Do something with request error
   return Promise.reject(error);
});

설정을 사용하여 현재 요청 리더에 액세스할 수 있습니다.header를 사용하여 다음과 같은 요구에 대해 헤더를 설정할 수 있습니다.

config.headers = {
   'Authorization': 'JWT ' + Vue.auth.getToken()
}

https://github.com/axios/axios

클래스를 만들어 선택한 헤더를 글로벌하게 추가할 수 있습니다.

import axios from 'axios';

/**
 * A wrapper around an axios instance, preconfigured to have a base URL and auth headers
 */
class Axios {
    constructor(baseUrl, bearerToken) {

        return axios.create({
            baseURL: baseUrl,
            headers: {
                Authorization: `Bearer ${bearerToken}`
            }
        });
    }
}

export default Axios;

그럼 당신의 앱에서.js

import { Axios } from 'my/class'


const myService = new Axios('baseURL', 'bearerToken');

asios.create를 사용해 본 적이 있습니까?

http/index.js:

import axios from 'axios'
import env from '../config/env'
import store from '../store'

export default (() =>
  axios.create({
    baseURL: env.API_HOST,
    headers: {
      common: {
        Authorization: store.getters['user/getAuthToken']
      }
    }
  }))()

main.js:

import http from './http'

Vue.prototype.$http = http

또한 store 액션을 사용하여 axios 클라이언트를 업데이트합니다.

updateHTTPClientAuthToken () {
  Vue.prototype.$http.defaults.headers.common.Authorization = this.getters.getAuthToken
}

언급URL : https://stackoverflow.com/questions/53930558/problem-when-modifying-axios-default-headers-globally-vue

반응형