Web/JavaScript

JavaScript - Axios (Ajax)

Axios

  • Promise 기반의 자바스크립트 비동기 처리방식
  • REST API 이용함

 

Axios 설치

  • 터미널 → npm install --save axios
  • import 하기 
  • import axios from 'axios'​

REST API

  • 가져오기: axios.get(url[, config])
  • 입력하기: axios.post(url[, config])
  • 부분 수정하기: axios.patch(url[, data[, config]])
  • 전체 수정하기: axios.put(url[, data[, config]])
  • 삭제하기: axios.delete(url[, config]))
// ID 조회 (GET)
axios.get('/user?ID=12345')
  .then(function (response) {
    // 성공 실행 코드
    console.log(response);
  })
  .catch(function (error) {
    // 에러 실행 코드
    console.log(error);
  })
  .then(function () {
    // 항상 실행 코드
  });

// 이렇게도 사용 가능 (GET)
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    // 성공 실행 코드
    console.log(response);
  })
  .catch(function (error) {
    // 에러 실행 코드
    console.log(error);
  })
  .then(function () {
    // 항상 실행 코드
  });  

// async/await 사용
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

 

// POST
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    // 성공 실행 코드
    console.log(response);
  })
  .catch(function (error) {
    // 에러 실행 코드
    console.log(error);
  });

 

// Axios API
axios({
  method: 'get',
  url: 'http://bit.ly/2mTM3nY',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });

 

Request 옵션

  • method: 요청 메소드
  • url: 요청 URL
  • headers: 요청 헤더
    // headers 예제
    axios.post(
      'url',
      {
        "body": data
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )
  • params: URL 파라미터 이용
  • data: 요청 Body 이용
  • timeout: 시간 제한 (기본값: 0[제한 없음])
  • responseType: 응답 타입 (기본값: json)

 

참고 링크 1: https://github.com/axios/axios#request-config

 

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

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

github.com

참고 링크 2: https://uxgjs.tistory.com/138

 

Vue.js에서 axios를 사용하여 서버통신하는 방법

웹 또는 앱을 개발하다 보면 거의 대부분이 서버가 필요하게 됩니다. 서버에 내용을 저장하고 웹이나 앱에서 서버의 저장된 내용을 불러다가 사용자에게 보여주게 되는데요. 이때 javascript에는 a

ux.stories.pe.kr

 

진행 상황 표시: https://gist.github.com/virolea/e1af9359fe071f24de3da3500ff0f429

 

Tracking file upload progress using axios

Tracking file upload progress using axios. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com