HJW's IT Blog

[CodeIt] 6월 4주차_02 본문

카테고리 없음

[CodeIt] 6월 4주차_02

kiki1875 2024. 6. 28. 12:53

Request 보내기

fetch 함수

  • 기본적으로 get request 를 보내고 promise 를 return 한다
const res = await fetch('url');
const data = await res.json();

res.status // request 의 상태
res.headers // json 으로 넘어오는 body
  • next url 에는 다음 값들을 받기 위한 url 이 포함된다
  • const url = new URL(’url’);
  • url.searchParams.append(’offset’,10);
  • url.searchParams.append(’limit’,10);
  • 위와 같이 파라미터를 조절할 수 있다
  • post 혹은 다른 종류의 request 는 다음과 같이 옵션을 넣어주어 보낼 수 있다
const surveyData = {
	mbti: 'ENFP',
	colorCode: '#ABCDEF',
	pwd: '0000',
}

const res = await fetch('url', {
	method: 'POST',
	body : JSON.stringify(surveyData), 
	headers:{
		'Content-Type': 'application/json',
	}
});

const data = await res.json();
console.log(data); 

API 함수 만들기

  • 웹 개발을 할 때 api 관련 코드를 한곳에 모아두고 호출하여 사용한다.
export async function getColorSurveys(params = {}){
	const url = new URL('url');
	Object.keys(params).forEach((key) => 
		url.searchParams.append(key, params[key])
	);
	
	const res = await fetch(url);
	const data = await res.json();
	return data;
}
import {getColorSurveys } from './api.js'

const data = await getcolorSurveys();
console.log(data);

오류 처리

  • try catch 문을 사용한다
  • 하지만 서버의 에러로 인한 status 500 과 같은 에러는 잡지 못한다.
    • 응답이 오면 promise 는 fulfilled 상태가 되기 때문이다
  • 즉, !res.ok 를 사용하여 응답 상태를 확인해야 한다

AXIOS 문법

  • npm install axios
  • axios 또한 promise 를 반환한다
const instance = axios.create({
	baseURL: 'url',
	timeout: 3000,
});
export async function getcolorSurvey(id){
	const res = await instance.get('url');
	return res.data;
}

export async function getcolorSurveys(params = {}) {
	const res = await instance.get('url', { params });
	return res.data;
}

export async function createColorSurvey(surveydata){
	const res = await instance.post(
		'url',
		surveydata,
	);
	
}
import axios from 'axios';

const instance = axios.create({
  baseURL: '<https://learn.codeit.kr/api>',
});

export async function getAvatars(params = {}) {
  const res = await instance.get('/avatars', {
    params,
  });
  return res.data;
}

export async function getAvatar(id) {
  const res = await instance.get(`/avatars/${id}`);
  return res.data;
}

export async function createAvatar(avatarData) {
  const res = await instance.post('/avatars', avatarData);
  return res.data;
}

export async function patchAvatar(id, avatarData) {
  const res = await instance.patch(`/avatars/${id}`, avatarData);
  return res.data;
}

export async function deleteAvatar(id) {
  const res = await instance.delete(`/avatars/${id}`);
  return res.data;
}

그렇다면 axios 를 사용한 400 혹은 500 대의 response 가 돌아온다면 어떻게 될까?

  • promise 가 rejected 상태로 남는다
  • axios 함수를 try catch 로 감싸면 된다

GET request 비교

// axios

export async function getColorSurveys(params = {}) {
  const res = await axios.get('<https://learn.codeit.kr/api/color-surveys>', {
    params,
  });
  return res.data;
}

// fetch
async function getColorSurveys(params = {}) {
  const url = new URL('<https://learn.codeit.kr/api/color-surveys>');
  Object.keys(params).forEach((key) =>
    url.searchParams.append(key, params[key])
  );
  const res = await fetch(url);
  const data = await res.json();
  return data;
}

POST request 비교

// axios

async function createColorSurvey(surveyData) {
  const res = await axios.post('<https://learn.codeit.kr/api/color-surveys>', surveyData);
  return res.data;
}

// fetch

async function createColorSurvey(surveyData) {
  const res = await fetch('<https://learn.codeit.kr/api/color-surveys>', {
    method: 'POST',
    body: JSON.stringify(surveyData),
    headers: {
      'Content-Type': 'application/json',
    },
  });

  if (!res.ok) {
    throw new Error('데이터를 생성하는데 실패했습니다.');
  }
//axios instance
const instance = axios.create({
  baseURL: '<https://learn.codeit.kr/api>',
  timeout: 3000,
});

async function getColorSurveys(params = {}) {
  const res = await instance.get(`/color-surveys`, {
    params,
  });
  return res.data;
}
//axios error handling
import { createColorSurvey } from './api.js';

const surveyData = {
  mbti: 'EEEE',
  colorCode: '#CDCDCD',
  password: '0000',
};

try {
  const newColorSurvey = await createColorSurvey(surveyData);
  console.log(newColorSurvey);
} catch (e) {
  if (e.response) { 
    // 리퀘스트는 성공했지만 상태 코드가 실패(4XX, 5XX)를 나타냄
    console.log(e.response.status);
    console.log(e.response.data);
  } else { 
    // 리퀘스트 자체가 실패
    console.log('리퀘스트가 실패했습니다.');
  }
}