본문 바로가기
CodeIt_Sprint/자바스크립트_Request보내기

(7)자바스크립트_리퀘스트_fetch()메소드 대신 더 간편한 문법 => axios 문법 //시발 처음부터 이렇게 알려주던가

by 코잼민 2024. 12. 8.

● 이론0_리퀘스트 fetch 문법 복습

//api.js

//1_ limit, offset 설정 후, API 데이터 fetch하기
export async function getColorSurveysLO(params = {})
{
	const url = new URL('https://learn.codeit.kr/api/color-surveys');
    
    //url에 limit , offset 설정 코드
    Object.keys(params).forEach((key)=>{
    	url.searchParams.append(key,params[key]);
    });
    
    //설정된 url를 기반으로 API에 fetch
    const res = await fetch(url);
    const data = await res.json();
    
    return data;
}

//2_ id를 입력하면, 해당 특정 id의 데이터만 API에서 fetch하기
export async function getColorSurveyById(id)
{
	const url = new URL(`https://learn.codeit.kr/api/color-surveys/${id}`);
    
    const res = await fetch(url);
    
    const data = await res.json():
    
    return data;
}

//3_ API에 데이터 추가하기 => POST 리퀘스트
export async function getColorSurveyById(surveyData)
{
	const url = new URL(`https://learn.codeit.kr/api/color-surveys/${id}`);
    
    const res = await fetch(url , {
    	method : "POST",
        body : JSON.stringify(surveyData),
        headers : {
        	"Content-type" : "application/json",
        },
    });
    
    const data = await res.json():
    
    return data;
}

● 이론1_axios를 이용해 저런 ㅄ같은 코드보다 더 간단하게 작성 구현 가능해짐

○ 여기서 배우는 axios의 기능

  • fetch 메소드 대신, axios 객체 프로퍼티 메소드 get , post (url)을 사용한다.
  • ★ API 데이터를 URL에서 인출한 뒤의 json()메소드를 이용해, json형태로 데이터를 형변환 할 떄, await을 할필요가 없어졌다. => 주요 기능 //쉽게 말하면, Parsing 단계가 짧아짐
  • limit, offset으로 API 데이터를 인출할 때, axios.get()메소드의 Argument에 Params 객체를 그냥 쳐넣기만 하면 된다. //처음부터 이렇게 알려주지 시발련이
  • axios.post(url , post할 데이터 객체 , method , body , headers정보가 적힌 객체 이것도 생략해도됨 ) ;
  • axios.create()메소드를 이용해, url의 base 태그 기능 + 비동기 setTimeout() 역할도 가능해짐

● 이론2_ axios 사용 방법 : 환경 setting 법 => axios는 서브파티모듈이다. => npm 터미널 명령어로 설치한다.

○ 순서1_ Ctrl + '`'//슬래시 백 키 를 눌러, 터미널창을 연 뒤, 아래의 터미널 명령어 작성한다.

npm install axios

그러면 탐색기에 모듈과 json이 생성된다.

○ 순서2_ 모든 fetch() 메소드가 모인 , 즉 모든 리퀘스트를 다루는 js 파일에 axios 서브 모듈 파티를 import한다.

import axios from 'axios';//axios를 import

const url = new URL('https://learn.codeit.kr/api/color-surveys');

 

● 이론3_ 모든 API 데이터 GET 리퀘스트 메소드를 axios로 바꿔보기

○ 이전 fetch 문법으로 구현한 코드 :

import axios from 'axios';//axios를 import


export async function getColorSurveys()
{
	const url = new URL('https://learn.codeit.kr/api/color-surveys');
	const res = await fetch(url);
    const data = await res.json();
    
    return data;
}

 

○ axios 문법으로 구현 코드_버전1 :

import axios from 'axios';


export async function getColorSurveys()
{
	const url = new URL('https://learn.codeit.kr/api/color-surveys');
	const res = await axios.get(url);
  //fetch() 대신 ,axios객체 프로퍼티 메소드 get(url)

  //Parsing 단계를 axios의 Promise 객체의 data 프로퍼티로 비동기 없이 반환 가능 //시발
  return res.data;
  
}

 

○ axios 문법 + axios 객체 프로퍼티 메소드 create() 로 구현 코드_버전2 :

바뀐 문법 목록 :

  • url객체 => axios.create({baseURL ,timeout })
  • 전부 GET 리퀘스트 문법 : fetch(url) => axios객체.get(url);
  • Parsing 과정 : const data =  res.json() => return res.data // axios의 Promise 객체 프로퍼티 data 
import axios from 'axios';

//axios.create(
	{baseURL , setTimeout 가 담긴 객체}
)
//=> 이새끼가 axios 객체 대신임

const instance = axios.create({
	baseURL : "https://learn.codeit.kr/api",//초반에 배운 base태그 역할
    timeout : 3000,//3초의 setTimeout()메소드 기능
);


export async function getColorSurveys()
{
    //instance 객체가 get() 호출
	const res = await instance.get('/color-surveys');


  //Parsing 단계를 axios의 Promise 객체의 data 프로퍼티로 비동기 없이 반환 가능 //시발
  return res.data;
  
}

● 이론4_ API 데이터를 limit , offset 설정한 후,  GET 리퀘스트

○ 이전 fetch 문법으로 구현한 코드 :

export async function getColorSurveysLO(params = {})
{
	const url = new URL('https://learn.codeit.kr/api/color-surveys');
    
    //url 객체에 limit, offset 설정 코드
    Object.keys(params).forEach((key)=>{
    	url.searchParams.append(key,params[key]);
    });
    
	const res = await fetch(url);
    const data = await res.json();
    
    return data;
}

 

○ axios 문법으로 구현 코드_버전1 :

※참고_ params가 null이면, Default limit, offset 없이 그냥 fetch 한다.

import axios from 'axios';//axios 서브 모듈 파티 import


export async function getColorSurveysLO(params={})
{
	const url = new URL('https://learn.codeit.kr/api/color-surveys');
	const res = await axios.get(url , {params});
  //fetch() 대신 ,axios객체 프로퍼티 메소드 get(url)
  //+ 매개인자에 limit, offset 가 들어있는 객체를 Argument 대입

  //Parsing 단계를 axios의 Promise 객체의 data 프로퍼티로 비동기 없이 반환 가능 //시발
  return res.data;
  
}

 

○ axios 문법 + axios 객체 프로퍼티 메소드 create() 로 구현 코드_버전2 :

import axios from 'axios';

const instance = axios.create({
  baseURL : "https://learn.codeit.kr/api",
  timeout : 3000,
})

async function getColorSurveysLO(params = {})
{
  const res = await instance.get("/color-surveys",{params})
  return res.data;
}

const data = await getColorSurveysLO({offset : 10 , limit : 10});

console.log(data);

 

● 이론5_ API 데이터에 데이터 추가하기 => Post 리퀘스트

○ 이전 fetch 문법으로 구현한 코드 :

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

 

○ axios 문법으로 구현 코드_버전1 :

※참고_ params가 null이면, Default limit, offset 없이 그냥 fetch 한다.

import axios from 'axios';//axios 서브 모듈 파티 import


export async function createColorSurvey(surveyData)
{
	const url = new URL('https://learn.codeit.kr/api/color-surveys');
	const res = await axios.post(url , surveyData);
  //post 리퀘스트 => axios 객체 프로퍼티 메소드 post(url , 삽입할 데이터 객체);

  //Parsing 단계를 axios의 Promise 객체의 data 프로퍼티로 비동기 없이 반환 가능 //시발
  return res.data;
  
}

 

○ axios 문법 + axios 객체 프로퍼티 메소드 create() 로 구현 코드_버전2 :

import axios from 'axios';

const instance = axios.create({
  baseURL : "https://learn.codeit.kr/api",
  timeout : 3000,
})

async function createColorSurvey(surveyData)
{
  const res = await instance.post("/color-surveys",surveyData)
  return res.data;
}

const surveyData = {
  mbti : "ISTJ",
  colorCode : "#ABCDEF",
  password : "0000",
};


const data = await createColorSurvey(surveyData);

console.log(data);

◎ 연습문제 :

실습 설명

api.js 파일에서 fetch() 대신 axios를 사용하도록 코드를 바꿔 보세요.

axios 인스턴스를 사용하면 중복되는 코드를 많이 줄일 수 있습니다. axios 패키지는 이미 설치된 상태입니다.

실습 결과

{
  count: 40,
  next: 'https://learn.codeit.kr/api/avatars/?offset=10&limit=10',
  previous: null,
  results: [
    {
      createdAt: 1688460577000,
      updatedAt: 1688460577000,
      id: 41,
      hairType: 'short2',
      hairColor: 'brown',
      skin: 'tone200',
      clothes: 'hoodie',
      accessories: 'earbuds'
    },
    {
      createdAt: 1688090371000,
      updatedAt: 1688090371000,
      id: 40,
      hairType: 'long1',
      hairColor: 'black',
      skin: 'tone300',
      clothes: 'knitLayered',
      accessories: 'none'
    },
    {
      createdAt: 1688090371000,
      updatedAt: 1688090371000,
      id: 39,
      hairType: 'none',
      hairColor: 'brown',
      skin: 'tone200',
      clothes: 'tshirtBasic',
      accessories: 'nametag'
    },
    {
      createdAt: 1688090371000,
      updatedAt: 1688090371000,
      id: 38,
      hairType: 'short2',
      hairColor: 'blonde',
      skin: 'tone300',
      clothes: 'hoodie',
      accessories: 'headset'
    },
    {
      createdAt: 1688090371000,
      updatedAt: 1688090371000,
      id: 37,
      hairType: 'long3',
      hairColor: 'brown',
      skin: 'tone400',
      clothes: 'knitVest',
      accessories: 'none'
    },
    {
      createdAt: 1688090371000,
      updatedAt: 1688090371000,
      id: 36,
      hairType: 'short1',
      hairColor: 'black',
      skin: 'tone100',
      clothes: 'tshirtPrinted',
      accessories: 'ballcap'
    },
    {
      createdAt: 1688090371000,
      updatedAt: 1688090371000,
      id: 35,
      hairType: 'long3',
      hairColor: 'brown',
      skin: 'tone300',
      clothes: 'tshirtPrinted',
      accessories: 'ballcap'
    },
    {
      createdAt: 1688090371000,
      updatedAt: 1688090371000,
      id: 34,
      hairType: 'short1',
      hairColor: 'black',
      skin: 'tone200',
      clothes: 'knitVest',
      accessories: 'earings'
    },
    {
      createdAt: 1688090371000,
      updatedAt: 1688090371000,
      id: 33,
      hairType: 'short2',
      hairColor: 'blonde',
      skin: 'tone100',
      clothes: 'dressFormal',
      accessories: 'headset'
    },
    {
      createdAt: 1688090371000,
      updatedAt: 1688090371000,
      id: 32,
      hairType: 'long1',
      hairColor: 'brown',
      skin: 'tone400',
      clothes: 'hoodie',
      accessories: 'none'
    }
  ]
}
{
  createdAt: 1688090371000,
  updatedAt: 1688090371000,
  id: 12,
  hairType: 'long3',
  hairColor: 'blonde',
  skin: 'tone400',
  clothes: 'jacketLeather',
  accessories: 'none'
}
{
  createdAt: 1688525364280,
  updatedAt: 1688525364280,
  id: 42,
  hairType: 'long1',
  hairColor: 'black',
  skin: 'tone100',
  clothes: 'hoodie',
  accessories: 'none'
}
{
  createdAt: 1688090371000,
  updatedAt: 1688525364316,
  id: 7,
  hairType: 'long1',
  hairColor: 'black',
  skin: 'tone300',
  clothes: 'tshirtBasic',
  accessories: 'headset'
}
  • ● 실제 결과는 위 예시와 조금 다를 수 있습니다.
  • DELETE 리퀘스트는 한 번 보내면 객체가 삭제되기 때문에 테스트 코드에 포함돼 있지 않습니다.
 

- main.js 

import axios from 'axios';

const instance = axios.create({
  baseURL : "https://learn.codeit.kr/api",
  timeout : 3000,
})

async function createColorSurvey(surveyData)
{
  const res = await instance.post("/color-surveys",surveyData)
  return res.data;
}

const surveyData = {
  mbti : "ISTJ",
  colorCode : "#ABCDEF",
  password : "0000",
};


const data = await createColorSurvey(surveyData);

console.log(data);

● 답 :

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;
}