axios

<aside> ๐Ÿ’ก ๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋Š” Javascript HTTP ํด๋ผ์ด์–ธํŠธ์ด๋‹ค.

HTTP์š”์ฒญ์„ Promise๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค.

์•„๋ž˜์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•œ๋‹ค.

catch์—์„œ error handling์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

const url = "<https://jsonplaceholder.typicode.com/todos>";

// axios ์š”์ฒญ ๋กœ์ง
axios
  .get(url)
  .then((response) => console.log(response.data))
	.catch((err) => {

		// ์˜ค๋ฅ˜ ๊ฐ์ฒด ๋‚ด์˜ response๊ฐ€ ์กด์žฌํ•œ๋‹ค = ์„œ๋ฒ„๊ฐ€ ์˜ค๋ฅ˜ ์‘๋‹ต์„ ์ฃผ์—ˆ๋‹ค	
		if (err.response) {
			
	    const { status, config } = err.response;
	
			// ์—†๋Š” ํŽ˜์ด์ง€
	    if (status === 404) {
	      console.log(`${config.url} not found`);
	    }

			// ์„œ๋ฒ„ ์˜ค๋ฅ˜
	    if (status === 500) {
	      console.log("Server error");
	    }
	
		// ์š”์ฒญ์ด ์ด๋ฃจ์–ด์กŒ์œผ๋‚˜ ์„œ๋ฒ„์—์„œ ์‘๋‹ต์ด ์—†์—ˆ์„ ๊ฒฝ์šฐ
	  } else if (err.request) {
	    console.log("Error", err.message);
		// ๊ทธ ์™ธ ๋‹ค๋ฅธ ์—๋Ÿฌ
	  } else {
	    console.log("Error", err.message);
	  }

</aside>

fetch

<aside> ๐Ÿ’ก ES6๋ถ€ํ„ฐ ๋„์ž…๋œ ๋‚ด์žฅ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ด๋‹ค.

Promise ๊ธฐ๋ฐ˜ ๋น„๋™๊ธฐ ํ†ต์‹  ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ด๋‹ค.

๋‹จ์ 

fetch์˜ ๊ฒฝ์šฐ catch์—์„œ ๋ฐœ์ƒํ•˜๋Š” ๊ฒฝ์šฐ๋Š” ์˜ค์ง ๋„คํŠธ์›Œํฌ ์žฅ์•  ์ผ€์ด์Šค์ด๋‹ค.

๊ฐœ๋ฐœ์ž๊ฐ€ ์ผ์ผํžˆ then()์•ˆ์— ๋ชจ๋“  ์ผ€์ด์Šค์— ๋Œ€ํ•œ HTTP ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ•œ๋‹ค.

const url = "<https://jsonplaceholder.typicode.com/todos>";

fetch(url)
  .then((response) => {
    if (!response.ok) {
      throw new Error(
        `This is an HTTP error: The status is ${response.status}`
      );
    }
    return response.json();
  })
  .then(console.log)
  .catch((err) => {
    console.log(err.message);
  });

</aside>