[React] 비동기 통신 axios (파일 업로드)

sua_ahn·2023년 5월 22일
0

React

목록 보기
6/6

Axios

: Promise API를 활용하며, 브라우저와 Node.js를 위해 만들어진 HTTP 비동기 통신 라이브러리

→ 백엔드와 프론트엔드가 쉽게 통신하기 위해 Ajax와 더불어 사용

  • 특징
    • HTTP 요청과 응답을 JSON 형태로 자동 변경
    • 구형 브라우저를 지원
      (운영환경에 따라 XMLHttpRequest 객체 또는 Node.js의 HTTP API를 사용)
    • CSRF 보호 기능 내장

Promise

: ES6에서 비동기 처리를 다루기 위해 사용되는 객체

콜백(callback)함수

비동기 방식에서 어떤 수행이 완료되었을 때 수행해야 할 함수

→ 비동기 작업의 결과를 그 다음 작업에 쓰고 싶다면,
비동기 작업과 그 이후 작업을 마치 동기 작업'처럼' 만들어주면 됨

async & await

async, await 를 사용하여 동기적으로 작동하는 것처럼 보일 수 있다.
동기적 순서로 처리할 일이 있는 비동기 작업에 await를 붙이고, 해당 작업을 포함하고 있는 함수에 async 를 붙이면 된다.

await는 혼자 쓸 수 없는데, await와 세트로 쓰는 것이 바로 async 다.

async는 선언된 함수 내에 비동기적으로 실행될 내용이 있다는 걸 알리는 거다. 그리고 그 비동기적으로 실행될 내용 앞에 await을 붙여서 표시한다. async를 붙인 함수는 Promise 객체를 반환한다.

await 을 Promise 객체 앞에 붙여 pending 상태에서 fulfilled 상태로 완료될때까지 대기한다. (메인 작업들은 멈추지 않고 await을 포함하고 있는 함수만 일시 정지)


간단한 사용 예시

  1. 라이브러리 설치
    npm install axios

  2. 파일 업로드, 다운로드

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function App() {

  const [number, setNumber] = useState();
  const [name, setName] = useState();
  const [address, setAddress] = useState();

  // POST, 파일 업로드
  const onSubmit = (e) => {
    e.preventDefault();
    // alert('onSubmit');
    let formData = new FormData();
    formData.append("number", number);
    formData.append("name", name);
    formData.append("address", address);
    formData.append("uploadFile", document.frm.uploadFile.files[0]);
    
    axios.post("http://localhost:3000/fileupload", formData)
    .then(res => {
      console.log(res.data);
    })
    .catch(function(error) {
      alert('upload failed');
    });
  }
  
  
  // 파일 다운로드
  const download = async () => {
    let filename = "algorithm.png";
    const url = "http://localhost:3000/filedownload?filename=" + filename;
    
    // 방법1. anchor 태그 생성 및 클릭
    const download = document.createElement('a');
    download.setAttribute("href", url);
    download.setAttribute("download", filename);
    download.setAttribute("type", "application/json");
    download.click();

    // 방법2. window 사용
    // window.location.href = url;
  }

  return (
    <>
      <h1>File upload</h1>
      <form name="frm" onSubmit={onSubmit} encType="multipart/form-data">
        <input value={number} onChange={(e) => setNumber(e.target.value)} placeholder="번호" /><br/>
        <input value={name} onChange={(e) => setName(e.target.value)} placeholder="이름" /><br/>
        <input value={address} onChange={(e) => setAdress(e.target.value)} placeholder="주소" /><br/>
        
        <input type="file" name="uploadFile" accept='*' />
        <input type="submit" value="upload" />
      </form><br/><hr/>
          
      <h1>File download</h1>
      <button onClick={download}>download</button>
    </>
  );
}
export default App;

 

 

※ 참고 사이트
https://sudo-minz.tistory.com/28
https://sudo-minz.tistory.com/21
https://ssong10.github.io/posts/JS/%EB%B9%84%EB%8F%99%EA%B8%B0%EC%B2%98%EB%A6%AC
https://redux-advanced.vlpt.us/2/02.html

profile
해보자구

0개의 댓글