axios는 설치 후 import 해서 사용해야 한다.
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
}
});
가장 기본적인 axios 통신 형태이다.
아래는 단축키 처럼 사용할 수 있는 통신 방법들이다.
-> 서버에 데이터를 넘길 때 사용.
.then 으로 성공했을 때 응답을 받을 수 있고 .catch 로 에러를 처리할 수 있다.
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})//여기에 config 들어감
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
로그인으로 예를 들자면 data 에 {email, password} 을 담을 수 있고, 성공 시 res.headers.get("Authorization") 를 통해 서버에서 jwt 토큰을 발급받을 수 있다. 또한 없는 회원일 경우 catch를 통해 해당 문구를 띄울 수 있다.
서버에서 데이터를 가져올 때 사용하는 메서드 이다.
axios.get('/user',
params: { // config
ID: 12345
})
데이터 수정이나 새로운 리소스를 생성할 때 요청.
post는 여러번 호출하면 데이터가 계속 추가되지만 , put은 여러번 요청해도 결과값이 동일하다.
axios.put('/user',{firstName: 'Fred',} // config)
특정 데이터 삭제
axios.delete('/user', // config)
axios.post(url,{data}, {
headers: { "Content-Type": `application/json`}
}
config에는 헤더(header), 응답 초과시간 (timeout), 인자 값(params),withCredentials(쿠키값 전달),responseType(데이터 타입),proxy 옵션 등을 넣을 수 있다.
axios는 instance 를 만들어 커스텀 할 수 있다.
instance를 만들면 반복되는 코드들을 재사용 할 수 있다는 장점이 있다.
예를 들어 매 요청마다 보내줘야 하는 JWT 토큰이나 기본적인 URL 앞부분을 넣을 수 있다.
const instance = axios.create({
baseURL: process.env.REACT_APP_API_URL,
timeout: 1000 * 5,
headers: {
"Content-Type": "application/json"
}
})
.env 파일은 환경 변수 파일로 포트, DB관련 정보, API_KEY 등 외부에 유출시키면 안되는 정보를 담는데 필요하다.
REACT_APP_지정한 변수 = 값
형태로 저장하며 최상단에 위치시켜야 process.env.REACT_APP_API_URL 처럼 import 없이 사용이 가능하다.
추가로 env파일은 .gitignore파일(의도적으로 추적되지 않은 파일을 지정)에 넣어서 숨길 수 있다.
이 파일을 제외하고 커밋하도록 한다.
또한 이 파일을 수정하면 서버를 다시 띄워야 적용된다.
-> interceptor은 비동기 처리가 이루어지기 전에(then, catch) 요청이나 응답을 가로채 작업을 추가로 사용한 뒤 통신이 이루어지게 하는 기능이다.
헤더 수정, 인증 토큰 추가, 오류 처리, 요청 및 응답을 기록하는 역할을 하며 모든 요청 또는 응답에서 동일한 코드를 반복하지 않아도 되어서 코드가 더 간결해지고 유지 관리가 쉬워진다.
또한 create 할 때 반영이 안되는 오류가 생길때도 있다고 해서 이렇게 중간에 interceptor 해주는 게 좋다.
request가 전송되기 전에 실행되는 기능. 서버에 요청을 보내기 전에 다른 작업을 수행할 수 있다.
예) 매 요청마다 보내야 하는 access 토큰 추가
instance.interceptors.request.use((config) => {
const token = localStorage.getItem("token");
if (token) {
config.headers["Authorization"] = `Bearer ${token}`
}
return config;
})
response를 받은 후 실행되는 기능.
response가 호출 코드로 다시 전달되기 전에 response 데이터를 수정하거나, 오류를 처리하거나, 정보를 기록하거나, 다른 작업을 수행할 수 있다.
예) access 토큰 만료 시 refresh 토큰 재발급 요청 보냄. 받은 refresh 토큰을 다시 로컬에 저장하기.
instance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response.status === 401) {
localStorage.removeItem("token");
window.location.href = `${routes.home}`;
return Promise.resolve(error.response.data);
}
return Promise.reject(error.response);
const register = (data) => {
const { email, password, username } = data;
return instance.post('/join', {
email,
password,
username
})
}
instance를 이용해 이렇게 통신을 할 수 있다.
++ 추가로 공부할 것 : 비동기 처리하기. timeout으로 응답 속도 제한하기
axios 공식 링크
https://axios-http.com/kr/docs/handling_errors
restful api
https://velog.io/@park0eun/Axios-비동기통신으로-api-데이터-이용하기
axios
https://inpa.tistory.com/entry/AXIOS-📚-설치-사용
env
https://carmack-kim.tistory.com/110
interceptor
https://growing-jiwoo.tistory.com/85
잘봤어요 글!!