inblog logo
|
{CODE-RYU};
    React

    [React] 서버와 통신하기

    류재성's avatar
    류재성
    Jul 13, 2024
    [React] 서버와 통신하기
    Contents
    1. Fake API 2. fetch 통신하기
     
     

    1. Fake API

    JSONPlaceholder - Free Fake REST API
    JSONPlaceholder is supported by the following companies and Sponsors on GitHub, check them out 💖
    JSONPlaceholder - Free Fake REST API
    https://jsonplaceholder.typicode.com/
     
    notion image
     
    위의 사이트의 /posts 를 선택한다.
     
    jsonplaceholder.typicode.com
    https://jsonplaceholder.typicode.com/posts
     
    notion image
     
    json 데이터를 확인할 수 있다.
     

    2. fetch 통신하기

     
    page/post.js
    import React from 'react'; function Post(props) { async function download(){ let response = await fetch("https://jsonplaceholder.typicode.com/posts/3",{ method:"get" }); } return ( <div> </div> ); } export default Post;
     
    💡
    fetch 는 통신을 위해 사용하는 자바스크립트의 함수이다. 통신은 시간이 오래 걸리는 작업이기 때문에 동기적으로 실행된다면 통신 단계에서 프로그램이 멈추게 된다. 따라서 fetch 는 비동기로 처리되어야 한다. 따라서 async 를 사용해 download 함수를 비동기 처리한다. await 는 download 함수를 잠시 정지 시킨 후 비동기로 다른 작업을 완료 한다. 그 후 프로미스를 확인해 통신이 완료가 되면 함수를 실행한다.
     
     
    import React from 'react'; function Post(props) { const download = async () => { let response = await fetch("https://jsonplaceholder.typicode.com/posts/3", { method: "GET" }); let data = await response.json(); console.log(data); } return ( <div> <button onClick={download}>Download Post</button> </div> ); } export default Post;
     
    버튼을 만들어 download 함수를 실행한다.
     
    notion image
     
    서버에서 json 데이터를 받아온다.
    Share article
    Contents
    1. Fake API 2. fetch 통신하기

    {CODE-RYU};

    RSS·Powered by Inblog