React

RestfulAPI연동

asd135 2025. 6. 3. 01:18
728x90

REST

웹 아키텍쳐 스타일 중 하나로, 웹의 자원을 URL로 표현하고 HTTP 메서드를 통해 자원을 처리하는 방식을 말한다.

 

Fetch API를 사용한 API 요청

브라우저(크롬, 사파리 등) 내장 API로 추가적인 설치 불필요

Promise 기반으로 비동기 HTTP 요청을 수행할 수 있음 -> Promise는 JavaScript에서 비동기 작업을 처리하기 위한 객체. 

 

GET 요청

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((data) => console.log(data));

1. GET 요청을 보냄

2. .then((response)=> response.json()) : 서버로부터 받은 응답(response) 객체를 받아 JSON 객체로 변환

3. 콘솔에 출력 

 

then() 메서드

then()은 Promise가 fulfilled 상태가 되었을 때 실행되는 콜백 함수를 등록하는 메서드

promise.then(onFulfilled, onRejected);

onFulfilled: 비동기 작업이 성공했을 때 실행될 함수

onRejected: 실패했을 때 실행될 함수 (catch로 처리하는 것이 일반적)

 

POST 요청

데이터가 많거나 폼(Form)으로 비밀번호 등의 개인정보를 보낼 때 POST 메서드 사용.

method 옵션을 POST로 설정하고 headers 옵션으로 JSON 포맷을 사용한다고 알려줌.

body 옵션에 요청 데이터를 JSON 포맷으로 작성함. 

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: "Test",
    body: "I am testing!",
    userId: 1,
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data));

1. 첫 번째 인자로 URL, 두 번째 인자로 옵션 객체, 해당 요청이 POST 방식임을 알려주고, 헤더정보로 요청의 body가 JSON 형식임을 서버에 알려주는 HTTP 헤더이다. 서버는 이 정보를 보고 JSON으로 해석하게 됨.

2. body : 전송할 데이터를 객체로 만들고 JSON.stringify()로 문자열(JSON)로 변환  

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

export default function App() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
  }, []);

    // get요청
    const clickGetHandler = () => {
    fetch('http://localhost:3001/data?name=John&age=30', {
        method : "GET"
    })
    .then((res)=> {
        console.log(res) //콘솔에 출력
        return res.json() //JSON으로 변환
    })
    .then((data)=> {
        setData(data); //state값 변경
    })
    .catch((err)=>{
        setError(err.message); //에러가 발생한 경우 실행 
    })
  }

  // post요청
  const clickPostHandler = () => {
    fetch('http://localhost:3001/data', {
      method: 'POST', // post 타입
      headers: {
        'Content-Type': 'application/json', // 헤더 정보에 JSON 타입인 것을 알려줌
      },
      body: JSON.stringify({ name: 'John', age: 30 }), // body 정보로 객체를 넘기고 문자열로 변환
    })
      .then((res) => {
        console.log(res);
        return res.json();
      })
      .then((data) => {
        setData(data);
      })
      .catch((err) => {
        setError(err.message);
      });
  };

  return (
    <div>
      <h1>Fetch GET/POST 요청 예시</h1>
      
      {/* 에러가 있을 경우 빨간 글씨로 표시 */}
      {error && <p style={{ color: 'red' }}>에러: {error}</p>} 

      {data ? (
        <pre>{JSON.stringify(data, null, 2)}</pre>
      ) : (
        <p>데이터 불러오는 중...</p>
      )}

      <button onClick={clickGetHandler}>요청(GET)</button>
      <button onClick={clickPostHandler}>요청(POST)</button>
    </div>
  );
}

 

 

<pre> : HTML은 기본적으로 공백이나 줄바꿈을 무시하지만, <pre>태그 안에서는 공백, 줄바꿈이 그대로 유지

 


Axios를 사용한 API 요청

Axios는 브라우저, Node.js를 위한 HTTP 비동기 통신 라이브러리, 백엔드와 프론트엔드가 통신을 쉽게하기 위해 사용됨

특징: 자동으로 JSON 데이터 형식으로 변환 시켜 줌, 좀 더 많은 웹 브라우저를 지원함(fetch API는 구형 브라우저는 미지원), 라이브러리 설치가 필요함.

 

axios.get()

axios.get("url")
.then(response => {
// response
}).catch(error => {
// 오류발생시 실행
}).then(() => {
// 항상 실행
});

url에 단순히 get 요청만 보냄, 추가 데이터 없이 요청

axios.get("url", {
params: {
id: 123
}
})
.then(response => {
// response
}).catch(error => {
// 오류발생시 실행
}).then(() => {
// 항상 실행
});

url?id=123와 같은 형태의 get 요청을 보냄

axios.get("url", { parrams: {id: 123}})는 내부적으로 url?id=123 요청과 같음

 

axios.post()

axios.post("url", {
	username: "",
    password: ""
})
.then(response => {
	// response
}).catch(error => {
	// 오류발생시 실행
}).then(() => {
	// 항상 실행
});

쿼리스트링을 사용하지 않고 post 요청의 body으로 데이터를 전송 username, password는 HTTP 요청 본문에 JSON 형식으로 들어감

 

axios.put()

axios.put("url", {
	username: "",
    password: ""
})
.then(response => {
	// response
}).catch(error=>{
	// 오류발생시 실행
}).then(()=>{
	// 항상 실행
})

put은 이미 존재하는 리소스를 바꿀 때 사용하는 것이 REST 원칙, post는 새로 만들 때 사용

 

axios.delete()

axios.delete('/user?ID=12345')
.then(response=>{
	console.log(response);
})
.catch(error=>{
	console.log(error);
})
.then(()=>{
})

delete 메서드는 일반적으로 body가 비어 있음.

get과 비슷한 형태이지만 delete 메서드가 실행되면 삭제 프로세스가 진행된다.

 

fetch, axios 반환값 차이

fetch(url)
  .then(res => res.json())  // res.json()은 프로미스(Promise)를 반환
  .then(data => {
    setData(data);          // 실제 JSON 파싱된 데이터에 접근
  });


axios.get(url)
  .then(res => {
    setData(res.data);  // axios는 응답 데이터를 바로 res.data에 담아서 줌
  });