Get
fetch API ์ฌ์ฉ
fetch([URL]).then((response) => response.json()) .then((data) => console.log(data));
fetch([URL])
- URL ์ธ ์ธ์๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก Get ๋ฐฉ์ ์ฌ์ฉํด์ ์์ฒญ ์ ์ก- fetch ํจ์์ ๋ฆฌํด ํ์
์ Promise ํ์
๊ฐ์ฒด
then((response) => response.json())
- then ํจ์๋ฅผ ํตํด fetch ํจ์(Promise)๊ฐ ์ฑ๊ณต์ ์ผ๋ก ์ฒ๋ฆฌ๋์์ ๋์ ์๋ต(resolve)์ ๋ฐ์์ค๋ฉด HTTP Request
์ ๋ํ ๊ฒฐ๊ณผ๋ฅผ ๋ด๊ณ ์๋ Response
๊ฐ์ฒด๋ฅผ ์ป์ ์ ์์
then((data) => console.log(data));
- json()
ํจ์๋ Promise ํ์
๊ฐ์ฒด๋ฅผ ๋ฐํํ๊ธฐ ๋๋ฌธ์ then ํจ์๋ฅผ ์ด์ฉํด์ resolve ํด์ฃผ๋ json ํ์์ ๋ฐ์ดํฐ๋ง ๋ฐ์์ฌ ์ ์์ - ๋ฐ์์จ json ๊ฐ์ฒด๋ฅผ console์ ํ์ํ๊ฑฐ๋, DOM์ ๋ฟ๋ฆฌ๋ ๋ฑ ์ ์ ํ๊ฒ ์ฒ๋ฆฌํ๋ฉด ๋จ!
Client์์ Request๋ฅผ ์ ์กํ๊ณ ์๋ต์ ์ฒ๋ฆฌํ๋ ์๋๋ฆฌ์ค ์ ๋ฆฌ
- GET
.then((response) => response.json()) // json ๊ฐ์ฒด๋ก ๋ง๋ค์ด์ง ๋ฐ์ดํฐ๊ฐ data์ ๋ด๊น // data๋ฅผ ์ถ๋ ฅ, ๋๋ ํ์ํ ๋ฐ์ดํฐ๋ฅผ ์ ์ ํ๊ฒ ํ์ฉํ๊ธฐ .then((data) => console.log(data)); // fetch API ์ฌ์ฉfetch([URL]) // URL ์ธ ์ธ์๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก Get ๋ฐฉ์ ์ฌ์ฉํด์ ์์ฒญ ์ ์ก // response๋ promise ๊ฐ์ฒด์ // ์๋ฒ๋ก๋ถํฐ ๋ฐ์ ํ์ํ ๋ฐ์ดํฐ๋ง ์ป๊ธฐ ์ํด์ json() ํจ์ ์ฌ์ฉ // json ํํ๋ก ๋ฐ์ดํฐ๋ฅผ ๋ฐ์์ด
- POST
// fetch API ์ฌ์ฉ let option = {// ์์ฒญ์ ์ฌ์ฉํ http method ๋ช ์ method: "POST", // ์์ฒญ์ ํ์ํ headerheaders: { // ์์ฒญ๊ณผ ํจ๊ป ์ ์กํ ๋ฐ์ดํฐ๊ฐ json ํํ์์ ์๋ฆผ "Content-Type": "application/json", }, // ์์ฒญ๊ณผ ํจ๊ป ์ ์กํ ๋ฐ์ดํฐ๋ฅผ ์ง๋ ฌํ (stringify, serialize) body: JSON.stringify(obj) }