일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 연습
- grpahQL
- 자바스크립트
- JavaScript
- underscores
- 클라이언트
- 해커톤
- 취업
- 리액트
- method
- 제일어려워
- 엔퀸즈
- 코딩
- 일상
- DOM
- nqueens
- ftech
- JS
- react
- 개발
- 코드스테이츠
- 포스기
- Instantiation Patterns
- underbar
- 초보
- array
- 알고리즘
- this
- 공부
- vscode
- Today
- Total
analogcoding
axios interceptors / defaults 본문
axios 요청을 사용하면서 생긴 불편함을 해결해주는 메소드 정리.
아래 적힌 일들을 해결하기 위해 axios 에서 제공해주는 interceptors / defaults 를 적용.
매번 axios 요청할때마다 URL 을 고정적으로 설정한다.
axios 요청을 할 때 마다 헤더를 고정적으로 설정해 놓는다.
에러가 발생했을때 공통 alert 를 띄운다.
요청 고정 URL 설정
const YOUR_URL = ''
axios.defaults.baseURL = YOUR_URL
로그인 이후에 모든 요청에 토큰을 보내는 설정
axios.defaults.headers.common["Authorization"] = ${localStorage.getItem("token")};
인터셉터는 요청 직전 혹은 응답을 받고 then, catch 코드를 타기 직전에 실행할 수 있다.
REQ
axios.interceptors.request.use(
config => {
// Request 보내기 전에 수행됨
// config 자체에는 request의 정보가 다 들어있음. url, headers, data 등
// config를 반환하거나, Promise.resolve(config)으로 반환하면 되는 듯
console.log(config)
return config
},
error => {
// Request 수행 중 오류 발생 시 수행됨
return Promise.reject(error);
},
)
RES
axios.interceptors.response.use(
function (response) {
// http status가 200인 경우 응답 성공 직전 실행.
// .then()
return response;
},
function (error) {
// http status가 200이 아닌 경우 응답 에러 직전 실행.
// .catch()
return Promise.reject(error);
}
);
참조
https://github.com/axios/axios
axios/axios
Promise based HTTP client for the browser and node.js - axios/axios
github.com
https://yamoo9.github.io/axios/guide/interceptors.html
인터셉터 | Axios 러닝 가이드
인터셉터 then이나catch로 처리되기 전에 요청이나 응답을 가로챌 수 있습니다. axios.interceptors.request.use( function (config) { return config; }, function (error) { return Promise.reject(error); }); axios.interceptors.response.use( function (response) { return response; }, function (e
yamoo9.github.io
Config 기본 설정 | Axios 러닝 가이드
Config 기본 설정 모든 요청에 적용될 구성 기본(Config Defaults) 값을 지정할 수 있습니다. 글로벌 axios 기본(defaults) 설정 axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'applic
yamoo9.github.io
'Be well coding > Learn more' 카테고리의 다른 글
StoryBook 사용 - 번역 (0) | 2020.04.28 |
---|---|
Github action 을 이용한 S3 배포 - 번역 (0) | 2020.04.22 |
React hooks 를 사용해야하는 이유 - 번역 (0) | 2020.02.18 |
styled-components 를 사용하는 8가지 이유 -번역 (0) | 2020.02.14 |
Webpack - React with typescript 초기 설정 (1) | 2020.01.21 |