μ›Ή 개발/React.js

React.js(8) - FetchGET&POST

SolartheNomad 2023. 4. 5. 17:18

πŸ‘©‍πŸ’» FetchGET 

http://example.com?a=1&b=2

 

- url ? 뒀에 νŒŒλΌλ―Έν„°=κ°’ $νŒŒλΌλ―Έν„°2=κ°’ ν˜•νƒœλ‘œ ν•„μš”ν•œ 데이터λ₯Ό μ „λ‹¬ν•œλ‹€.

- 주둜 데이터 μ‘°νšŒλ‚˜ 검색 λ“±μ˜ κΈ°λŠ₯에 μ‚¬μš©λ¨ 

- 데이터λ₯Ό μ‘°νšŒν•΄ 가져와 μ‚¬μš©ν•˜κΈ° μœ„ν•œ λ©”μ„œλ“œ

 

 

✍ FetchGet.js

import React, {Component} from 'react';

class R059_FetchGet extends Component {
    componentDidMount= async ()=>{
        const response = await fetch('http://date.jsontest.com/');
        const body = await response.json();
        alert(body.date);
    }
    
    render() {
        return (
            <h1>fetch get</h1>
        )
    }
}

export default R059_FetchGet;

 

πŸ’šasync- await λ©”μ„œλ“œ

✍ ν˜•νƒœ

 componentDidMount= async ()=>{
        const response = await fetch('http://date.jsontest.com/');
        const body = await response.json();
        alert(body.date);
    }

 

- JavaScriptμ—μ„œ 비동기적인 처리λ₯Ό κ°„κ²°ν•˜κ²Œ μž‘μ„±ν•  수 μžˆλ„λ‘ ν•˜λŠ” λ©”μ„œλ“œ

- Promise 객체λ₯Ό λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜λ₯Ό 마치 동기적인 μ½”λ“œμ²˜λŸΌ μž‘μ„±ν•  수 μžˆλ‹€.(사싀 λΉ„λ™κΈ°μ μž„)

- async ν‚€μ›Œλ“œλ‘œ ν•¨μˆ˜λ₯Ό μ„ μ–Έν•˜λ©°, ν•¨μˆ˜ λ‚΄μ—μ„œ await ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•˜μ—¬ Promise 객체λ₯Ό μ²˜λ¦¬ν•œλ‹€.

- await ν‚€μ›Œλ“œλŠ” Promise 객체가 처리될 λ•ŒκΉŒμ§€ μ½”λ“œμ˜ 싀행을 μΌμ‹œ μ€‘μ§€ν•˜κ³ , 처리 κ²°κ³Όλ₯Ό λ°˜ν™˜ν•œλ‹€. 

- async-await ν•¨μˆ˜λŠ” try-catch ꡬ문과 ν•¨κ»˜ μ‚¬μš©ν•˜μ—¬ 비동기적인 처리 쀑 λ°œμƒν•  수 μžˆλŠ” 였λ₯˜λ₯Ό μ²˜λ¦¬ν•  수 μžˆλ‹€.

- response.json() 쀑 date νƒ€μž… λ°μ΄ν„°λ“€λ§Œ alert ν•¨μˆ˜λ‘œ λ°˜ν™˜ν•΄μ€€λ‹€. 

 

 

🐀 try - catch 

async function fetchExample() {
  try {
    const response = await fetch('https://example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
}

- fetch() ν•¨μˆ˜λ‚˜ json() λ©”μ„œλ“œμ—μ„œ 였λ₯˜κ°€ λ°œμƒν•  경우, catch κ΅¬λ¬Έμ—μ„œ 였λ₯˜λ₯Ό μ²˜λ¦¬ν•˜κ³  μ—λŸ¬ λ©”μ‹œμ§€λ₯Ό μ½˜μ†”μ— 좜λ ₯ν•΄μ€€λ‹€.

 

πŸ“Œ try-catch

- μ˜ˆμ™Έ 처리λ₯Ό ν•  λ•Œ μ‚¬μš©ν•˜λŠ” ꡬ문

- try λΈ”λ‘μ—λŠ” μ˜ˆμ™Έκ°€ λ°œμƒν•  κ°€λŠ₯성이 μžˆλŠ” μ½”λ“œλ₯Ό μž‘μ„±ν•˜κ³ , catch λΈ”λ‘μ—λŠ” μ˜ˆμ™Έκ°€ λ°œμƒν–ˆμ„ λ•Œ μ²˜λ¦¬ν•  μ½”λ“œλ₯Ό μž‘μ„±ν•œλ‹€.

try {
  const result = 10 / 0; // 0으둜 λ‚˜λˆ„κΈ°
  console.log(result);
} catch (error) {
  console.error(error);
}

- 10을 0으둜 λ‚˜λˆ„λŠ” μ½”λ“œλ₯Ό μž‘μ„±ν–ˆλŠ”λ°, μ΄λŠ” μœ νš¨ν•˜μ§€ μ•Šμ€ κ³„μ‚°μ΄λ―€λ‘œ μ˜ˆμ™Έκ°€ λ°œμƒν•œλ‹€. μ΄λ•Œ catch λΈ”λ‘μ—μ„œλŠ” μ˜ˆμ™Έλ₯Ό μ²˜λ¦¬ν•˜κ³  μ—λŸ¬ λ©”μ‹œμ§€λ₯Ό 좜λ ₯ν•˜κ²Œ 됨

 

πŸ“Œ 파일 μ½μ–΄μ˜€λŠ” μ½”λ“œ μ˜ˆμ‹œ μž‘μ„±

try {
  const data = readFile('data.txt'); // 파일 읽기
  console.log(data);
} catch (error) {
  if (error.code === 'ENOENT') {
    console.error('File not found'); // 파일이 μ—†λŠ” 경우
  } else {
    console.error(error); // 기타 였λ₯˜
  }
}

 

 

πŸ’š Promise 객체

- λΉ„λ™κΈ°μ²˜λ¦¬λ₯Ό μœ„ν•œ 객체

- 비동기 μž‘μ—…μ΄ μ™„λ£Œλ  λ•ŒκΉŒμ§€ 기닀리지 μ•Šκ³  λ‹€μŒ μž‘μ—…μ„ μ²˜λ¦¬ν•  수 μžˆλ„λ‘ ν•΄μ€€λ‹€.

 

πŸ’š Promise 객체 μƒνƒœ

 

  • λŒ€κΈ°(pending) μƒνƒœ: 비동기 μž‘μ—…μ΄ 아직 μ™„λ£Œλ˜μ§€ μ•Šμ€ μƒνƒœ
  • 이행(fulfilled) μƒνƒœ: 비동기 μž‘μ—…μ΄ μ„±κ³΅μ μœΌλ‘œ μ™„λ£Œλœ μƒνƒœμ΄λ©°, μ΄λ•Œ κ²°κ³Ό 값이 μ „λ‹¬λœλ‹€.
  • κ±°λΆ€(rejected) μƒνƒœ: 비동기 μž‘μ—…μ΄ μ‹€νŒ¨ν•œ μƒνƒœμž…λ‹ˆλ‹€. μ΄λ•Œ 였λ₯˜ 정보가 전달됨

 

 

 

 

πŸ’š fetch

const response = await fetch('http://date.jsontest.com/');

- HTTP μš”μ²­μ„ 보내고 응닡을 λ°˜ν™˜ν•œλ‹€.

- APIμ—μ„œ 데이터λ₯Ό κ°€μ Έμ™€μ„œ λ°˜ν™˜ν•΄μ€€λ‹€. 

- await둜 fetch의 λ°˜ν™˜κ²°κ³Όλ₯Ό κΈ°λ‹€λ¦°λ‹€. 

 

 

 

πŸ’š response.json()

const body = await response.json();

- 이후 response.json() λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ—¬ 응닡을 JSON ν˜•νƒœλ‘œ λ³€ν™˜ν•¨

 

 

πŸ’š FetchPOST

- url 뒀에 νŒŒλΌλ―Έν„°λ₯Ό ν‘œμ‹œν•˜μ§€ μ•Šκ³  μ‚¬μš©ν•¨(http body에 νŒŒλΌλ―Έν„°λ₯Ό λ„£μ§€ μ•ŠλŠ”λ‹€.)

- μ„œλ²„μ˜ μƒνƒœλ‚˜ 데이터λ₯Ό λ³€κ²½ν•˜λŠ” λ“±μ˜ μˆ˜ν–‰ μž‘μ—…μ— μ‚¬μš©λœλ‹€. 

 

 

✍ FetchPost.js

import React from "react";
import { Component } from "react";

class R060_FetchPost extends Component {
    componentDidMount=async ()=>{
        const response = awiait fetch('http://data.jsontest.com/', {
            #fetch 방법은 getκ³Ό λΉ„μŠ·ν•˜μ§€λ§Œ 두 번째 νŒŒλΌλ―Έν„°μ— post ν˜ΈμΆœμ— λŒ€ν•œ 정보가 μΆ”κ°€ λœλ‹€. 
            #Content-Type λ³€μˆ˜ : json ν˜•νƒœμ˜ 데이터λ₯Ό μ‚¬μš©ν•˜κΈ° μœ„ν•΄ application/json에 ν• λ‹Ήν•œλ‹€.
            method : 'POST',
            headers : {
                'Content-Type' : 'application/json',
            },
            body : {a:"react", b:200},

        });
        const body = await response.json();
        alert(body.date)


    }

    render () {
        return (
            <h1>fetch post</h1>
        )
    }
}

export default R060_FetchPost;