Web/React

React - Axios

또롱또 2022. 6. 28. 12:02
728x90

 

npm install axios
yarn add axios

Axios란

브라우저, Node.js를 위한 Promise API를 활용하는 HTTP비동기 통신 라이브러리이다.

 

기능

  • 브라우저 환경 XMLHttpRequests 요청 생성
  • Node.js 환경 http 요청 생성
  • Promise API 지원
  • 요청/응답 차단(Intercept)
  • 요청/응답 데이터 변환
  • 취소 요청
  • JSON 데이터 자동 변환
  • 사이트 간 요청 위조(XSRF)보호를 위한 클라이언트 사이드 지원

 

기본 사용방법

// Async await을 통한 방법

import axios from 'axios';

async function getUser() {
  try {
    const response = await axios.get('/userinfo');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

 

멀티 요청 방법

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));

 

HTTP 메서드 별칭과 구성옵션.

구성옵션에 넣을수 있는 거에 대해서는 아래 사이트 참고

https://yamoo9.github.io/axios/guide/api.html#%EA%B5%AC%EC%84%B1-%EC%98%B5%EC%85%98

axios.get(url[, config])            // GET
axios.post(url[, data[, config]])   // POST
axios.put(url[, data[, config]])    // PUT
axios.patch(url[, data[, config]])  // PATCH
axios.delete(url[, config])         // DELETE

axios.request(config)
axios.head(url[, config])
axios.options(url[, config])

 

Interceptors

- 인터셉터란 요청을 처리하기 전에 요청이나 응답을 가로 챌 수 있다.

- 즉 서버와 요청함에 있어서 중간 미들웨어를 설정할 수 있다.

 

예시)

로그인 후, 사용자가 무언가를 진행하려 할때 (CRUD등)

우리는 서버에 토큰값을 보내줘서 이 사용자가 누군지 알려줘야한다.

그런경우 

// api가 axios.create으로 만들어졌단 가정하에

// Request에 관한 Interceptor
// 우리가 보낼때에 관련된거다
api.interceptors.request.use(config => {
  // 보낼거 처리
  config.headers['Content-Type'] = 'application/json; charset=utf-8';
  config.headers['X-Requested-With'] = 'XMLHttpRequest';
  config.headers.token = getCookie();
  config.headers.Accept = 'application/json';

  return config;
  },
    error => {
        // 에러발생하면 여기
        console.log(error);
    }

);

// Response에 관한 Interceptor
// 우리가 받을거에 관련된거다,  401오류 처리를 axios를 전역으로 관리
api.interceptors.response.use(
  response => {
    return Promise.resolve(response);
  },
  error => {

    return Promise.reject(error);
  },
);

return response로 처리하면 오류가 발생했을때 아무 데이터도 담겨있지않은 response가 들어와서 redux가 비어버리는 문제가 발생해서 그 부분을 막기 위해서 Promise.resolve(resposne)로 처리.

 

이렇게 처리하면 제대로 response가 들어왔을때만 처리해주기 때문에 빈 데이터가 통과되는 문제를 피할수있다.

 

또 아래에 에러문도 redux내에서 catch로 사용한 에러를 발생시키기 위해서 return Promise.reject(error)를 사용해서 401에러가 아닐시에는 catch문으로 가도록 처리한것이다. 이 부분을 유의해서 사용하면 좀 더 편리하게 사용할 수 있다.

 

인스턴스 생성으로 더 간편하게 관리하기

인스턴스 생성

const api = axios.create({
  baseURL: 'https://some-domain.com/api/',
  headers: { 'X-Custom-Header': 'foobar' },
  timeout: 1000, 
  // timeout이 설정되어 있지 않아서 설정 안해주면 서버가 응답할때까지 계속 연결
});

 

API 한번에 관리하기

export const apis = {
	// article
	add: (contents) => api.post('/api/articles', contents),
	edit: (id, contents) => api.put(`api/articles/${id}`, contents),
	del: (id) => api.delete(`api/articles/${id}`),
	articles: () => api.get('/api/articles'),
	article: (id) => api.get(`/api/articles/${id}`),
	search: (value) => api.get(`/api/articles/search?query=${value}`),

	// comment
	addComment: (id, content) =>
		api.post(`/api/articles/${id}/comments`, { content }),
	comments: (id) => api.get(`/api/articles/${id}/comments`),
	delComment: (id, coId) => api.delete(`/api/articles/${id}/comments/${coId}`),
	editComment: (id, coId, content) =>
		api.put(`/api/articles/${id}/comments/${coId}`, { content }),

	// user
	login: (id, pw) => api.post('/user/login', { username: id, password: pw }),
	signup: (id, email, pw, pwcheck) =>
		api.post('/user/signup', {
			username: id,
			email: email,
			password: pw,
			repassword: pwcheck,
		}),
	userInfo: () => api.get(`/myinfo`),
	userPassword: (pw) => api.post(`/myinfo`, pw),
	userNewPassword: (pw) => api.put(`/myinfo`, pw),
};

 

 

 

 

 

 

728x90

'Web > React' 카테고리의 다른 글

React -Chartjs  (1) 2022.06.29
React - CORS 오류 클라에서 처리 - proxy 설정  (0) 2022.06.25
React - 회원가입  (0) 2022.06.25
React - REACT QUERY + 우아한테크세미나 정리  (1) 2022.06.25
React - Emotion  (0) 2022.06.25