본문으로 바로가기

 

 

axios/axios

Promise based HTTP client for the browser and node.js - axios/axios

github.com

 

Axios Cheat Sheet - Kapeli

{ // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be conve

kapeli.com

 

 

백단과 프론트가 통신하기 위한 api로 Axios와 fetch가 존재한다. 지금까지는 주로 axios.get만을 이용해서 api에서 일방적으로 정보를 가져오는 것만 사용해보았지만 HTTP 메소드 전부를 axios를 통해 이용할 수 있다.

 

// []는 생략될 수 있음을 의미합니다.

axios.request(config)

axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])

axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

 

* async/await를 사용할지, .then을 사용할지는 자유이다. 자신이 편한 비동기 처리법을 사용하자.

 

⚡ 간단한 GET

 

가장 간단한 형태의 axios get 방식은 다음과 같다. (이와 같은 문법 사용을 위해서는 babel을 이용해야 한다. 설치가 귀찮다면 const axios = require("axios")와 같은 구 문법을 이용하자.)

import axios from "axios";

const load = async () => {
  try {
    const tickes = await axios.get(`https://api.coinpaprika.com/v1/tickers`);
    console.log(tickes);
  } catch (error) {
    console.log(error);
  } finally {
    //   Do something
  }
};

load();

 

Request config 객체 구성

 

params

baseURL

method(get이 default)

timeout(If the request takes longer than `timeout`, the request will be aborted. 기본값은 0[timeout 없음])

proxy

 

등이 존재한다. 매우 많으므로 공식 문서에서 직접 확인하길 추천한다. 위 속성들을 간단히 이용한 예시는 다음과 같다.

 

import axios from "axios";

const api = axios.create({
  baseURL: "https://api.themoviedb.org/3/"
});

const Params = {
  api_key: "1234",
  language: "en-US"
};

// https://api.themoviedb.org/3/tv/top_rated?api_key=1234&language=en-US의 정보 GET

const getTV = async () => {
  try {
    const TV = await api.get("tv/top_rated", { params: Params, timeout: 1 });
    console.log(TV)
  } catch(error) {
    console.log(error);
  } finally {
    // Do Something
  }
}

 

타임아웃을 0.001초로 잡아서 타임아웃 오류가 발생합니다.

 

 

⚡ 간단한 Post

 

앞서 axios.post(url[, data[, config]])의 형식으로 post를 보낸다는 걸 확인했다.

import axios from "axios"

const Data = {
  firstName: 'Fred',
  lastName: 'Flintstone'
}

const config = {
  status: 200,
  statusText: 'OK',
  headers: {}
}

axios.post('/user', Data, config)
  .then(response => console.log(response))
  .catch(error => console.log(error));

 

주로 서버에 보내는 정보는 Formdata를 통해 보내는 것이 대부분이다.

const addCustomer = () => {
  const url = `/api/customers`;
  const formData = new FormData();
  formData.append("image", file);
  formData.append("name", userName);
  formData.append("birthday", birthday);
  formData.append("gender", gender);
  formData.append("job", job);
  const config = {
    headers: {
      "content-type": "multipart/form-data",
    },
  };
  return axios.post(url, formData, config);
};

 

아, 그리고 포스트를 날릴 경우 package.json에서 설정한대로 proxy가 안 먹는 경우가 많으니까

아예 baseURL을 깔아버리는 게 마음 편하다. 

axios.defaults.baseURL = "http://localhost:5000/";

 

 

⚡ Response Schema

 

post 등 전송하는 명령시 추가할 수 있는 config의 요소들이다.

{
  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the HTTP headers that the server responded with
  // All header names are lower cased and can be accessed using the bracket notation.
  // Example: `response.headers['content-type']`
  headers: {}
}

'Programming Language > 🟨 Javascript' 카테고리의 다른 글

바닐라 JS로 Carousel Slider 만들기  (0) 2020.04.18
fetch 간단 활용법 정리  (0) 2020.04.11
window 객체  (0) 2020.04.07
[mo.js ]mo.js - 모션그래픽 라이브러리  (0) 2020.04.07
localStorage  (0) 2020.04.07

darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체