๐Ÿ”Žย fetch()

๊ฐ€์˜ค๋ฆฌยท2023๋…„ 2์›” 12์ผ
0

keyword

๋ชฉ๋ก ๋ณด๊ธฐ
4/6
post-thumbnail

fetch() ์‚ฌ์šฉ๋ฒ•

  • ์ฒซ ๋ฒˆ์งธ ์ธ์ž๋กœ URL, ๋‘๋ฒˆ์งธ ์ธ์ž๋กœ ์˜ต์…˜ ๊ฐ์ฒด๋ฅผ ๋ฐ›๊ณ  Promise ํƒ€์ž…์˜ ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
  • ๋ฐ˜ํ™˜๋œ ๊ฐ์ฒด๋Š” API ํ˜ธ์ถœ์ด ์„ฑ๊ณตํ–ˆ์„ ๊ฒฝ์šฐ ์‘๋‹ต ๊ฐ์ฒด๋ฅผ resolveํ•˜๊ณ  ์‹คํŒจํ–ˆ์„ ๊ฒฝ์šฐ ์˜ˆ์™ธ ๊ฐ์ฒด๋ฅผ reject ํ•œ๋‹ค.
  • ์˜ต์…˜ ๊ฐ์ฒด์—๋Š” HTTP ๋ฐฉ์‹(method), HTTP ์š”์ฒญ ํ—ค๋”(headers), HTTP ์š”์ฒญ ์ „๋ฌธ(body) ๋“ฑ์„ ์„ค์ •ํ•ด์ค€๋‹ค.
  • ์‘๋‹ต ๊ฐ์ฒด๋กœ๋ถ€ํ„ฐ๋Š” HTTP ์‘๋‹ต ์ƒํƒœ(status), HTTP ์‘๋‹ต ํ—ค๋”(headers), HTTP ์‘๋‹ต ์ „๋ฌธ(body) ๋“ฑ์„ ์ฝ์–ด์˜ฌ ์ˆ˜ ์žˆ๋‹ค.
fetch(url, options)
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error));


fetch()๋กœ HTTP ์š”์ฒญํ•˜๊ธฐ

  1. GET: ์กด์žฌํ•˜๋Š” ์ž์› ์š”์ฒญ

    • ๋‹จ์ˆœํžˆ ์›๊ฒฉ API์— ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ฌ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.
    • ๋””ํดํŠธ๋กœ GET ๋ฐฉ์‹์œผ๋กœ ์ž‘๋™ํ•˜๋ฉฐ ์˜ต์…˜ ์ธ์ž๊ฐ€ ํ•„์š” ์—†๋‹ค.
    • ์‘๋‹ต ๊ฐ์ฒด๋Š” json()์„ ์ œ๊ณตํ•˜๊ณ  ์ด ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ์‘๋‹ต ๊ฐ์ฒด๋กœ๋ถ€ํ„ฐ JSON ํ˜•ํƒœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค.
    fetch(url)
    	.then((response) => response.json())
    	.then((data) => console.log(data))

  1. POST: ์ƒˆ๋กœ์šด ์ž์› ์ƒ์„ฑ ์š”์ฒญ

    • ๋ฐ์ดํ„ฐ๋ฅผ ๋งŒ๋“ค์–ด ๋ณด๋‚ผ ๋•Œ๋Š” POSt ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.
    • ์ƒˆ๋กœ์šด ํฌ์ŠคํŠธ ์ƒ์„ฑ์„ ์œ„ํ•ด์„œ method๋ฅผ POST๋กœ ์ง€์ •ํ•œ๋‹ค.
    • headers ์˜ต์…˜์œผ๋กœ JSON ํฌ๋งท์„ ์‚ฌ์šฉํ•œ๋‹ค๊ณ  ์•Œ๋ ค์ฃผ๊ณ  body ์˜ต์…˜์—๋Š” ์š”์ฒญ ์ „๋ฌธ์„ JSON ํฌ๋งท์œผ๋กœ ๋„ฃ๋Š”๋‹ค.
    fetch(url, {
    	method: "POST",
    	headers: {
    		"Content-type": "application/json",
    	},
    	body: JSON.stringify({
    		title: "Test",
    		body: "Testing",
    		userId: 1
    	}),
    })
    	.then((response) => response.json())
    	.then((data) => console.log(data))
  1. PUT: ์กด์žฌํ•˜๋Š” ์ž์› ๋ณ€๊ฒฝ ์š”์ฒญ

    • API์—์„œ ๊ด€๋ฆฌํ•˜๋Š” ๋ฐ์ดํ„ฐ์˜ ์ˆ˜์ •์„ ์œ„ํ•ด ์‚ฌ์šฉํ•œ๋‹ค.
    • method ์˜ต์…˜์ด PUT์ธ ๊ฒƒ์„ ์ œ์™ธํ•˜๋ฉด POST ๋ฐฉ์‹๊ณผ ๋น„์Šทํ•˜๋‹ค.
    fetch(url, {
    	method: "PUT",
    	headers: {
    		"Content-type": "application/json",
    	},
    	body: JSON.stringify({
    		title: "Test",
    		body: "Test end",
    		userId: 1
    	}),
    })
    	.then((response) => response.json())
    	.then((data) => console.log(data))

  1. DELETE: ์กด์žฌํ•˜๋Š” ์ž์› ์‚ญ์ œ ์š”์ฒญ

    • ๋ณด๋‚ผ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์— headers, body ์˜ต์…˜์ด ํ•„์š” ์—†๋‹ค.
    fetch(url, {
    	method: "DELETE",
    })
    	.then((response) => response.json())
    	.then((data) => console.log(data))
profile
๊ฐ€์˜ค๋ฆฌ์˜ ์ฝ”๋”ฉ์ผ๊ธฐ

0๊ฐœ์˜ ๋Œ“๊ธ€