본문 바로가기

WIL

2022.2.2nd WIL

Axios

이번 프로젝트에서 프론트엔드는 React 환경에 Axios라는 라이브러리를 사용하여 Spring 서버와 HTTP 통신을 하기로 하여 Axios에 대한 글을 써본다.

Axios 특징

  • 운영 환경에 따라 브라우저의 XMLHttpRequest 객체 또는 Node.js의 http api 사용
  • Promise(ES6) API 사용
  • 요청과 응답 데이터의 변형
  • HTTP 요청 취소
  • HTTP 요청과 응답을 JSON 형태로 자동 변경
const api = axios.create({
    baseURL: '<http://localhost:3000>',
    headers: {
        'content-type': 'application/json;charset=UTF-8',
        accept: 'application/json,',
    },
});

api.defaults.headers.common['Authorization'] = 'success';

const TEST_URL = site => `http://localhost:3003/${site}`;

base url은 개발서버가 돌아가는 url이다.

 

TEST_URL은 json-server 라는 mocking server를 돌리고 있는 url로 설정돼있다.

 

const apis = {
	uploadImageUrl: url => api.post(TEST_URL('imageUrl'), { image_url: url })
	.....
}

위에서 생성한 Axios 객체를 apis라는 객체속의 메소드로 선언해주었다.

 

TEST_URL 뒤의 ('imageUrl') 은 http://localhost:3003/imageUrl 경로로

바디에 { image_url: 어떤이미지url } 이라는 json 객체를 담아서 보내는 구문이다.

 

getArticle: () => api.get(TEST_URL('articles')),

http://localhost:3003/articles 로 get 요청을 보내는 구문이다.

 

const checkLoginApi = (token) => {
  return function (dispatch, getState, { history }) {
    axios({
      method: "post",
      url: "<http://3.38.153.67/user/islogin>",
      headers: {
        "content-type": "applicaton/json;charset=UTF-8",
        accept: "application/json",
        Authorization: `${token}`,
      },
    })
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });
  };
};

 

 

headers: { } 안에 Authorization token을 보내지 않아서 한참 로그인이 안됐었으나 해결!!

 

Axios는 왠지 어려울것 같은 이름을 가졌지만, HTTP 요청을 간단하게 만들어주는 매우 고마운 툴이라고 느꼈다.

'WIL' 카테고리의 다른 글

2022.2.4th ~ 3.1st  (0) 2022.03.07
2022.2.3rd WIL  (0) 2022.02.20
2022.2.1st WIL  (0) 2022.02.07
2022.1.4th WIL  (0) 2022.01.31
2022.1.3rd WIL  (0) 2022.01.24