본문 바로가기

학습노트/기초지식

[axios] axios와 사용법

axios란?

  HTTP Cilent 라이브러리로써, 비동기 방식으로 HTTP 데이터 요청을 할 수 있다. 또한 내부적으로는 직접적인 XMLHttpRequest를 다루지 않고 'Ajax 호출'을 할 수 있다.

 

 

Ajax란?

  Asynchronous Javascript And XML의 약자로 jQuery의 비동기적인 웹 애플리케이션을 제작할때 사용하는 기법이다. 비동기식 자바스크립트 XML이라고 할 수있다.

 

 

axios 설치방법

npm install --save axios

 

 

axios 사용방법

설치 후 서버 파일이 될 js파일 상단에 선언해준다.

const axios = require("axios");

 

 

GET API 호출

const axios = require('axios');
 
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });
 
// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  
 
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

 

 

POST API 호출

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

 

 

PUT API 호출

axios.PUT('/user?ID=12345', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

 

 

DELETE API 호출

axios.delete('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });