댓글 검색 목록

[javascript] JavaScript의 Axios 용 치트 시트

페이지 정보

작성자 운영자 작성일 21-07-06 21:53 조회 1,588 댓글 0

Axios는 요청을 만들고 API를 사용하는 데 사용됩니다.


NodeJS 환경에서 작업 할 것입니다.


Axios 설치 


npm install axios 


Axios 가져 오기 


const axios = require('axios') 


받기 요청하기 


With Promises (without async/await) 


const axios = require("axios"); const url = "https://jsonplaceholder.typicode.com/todos/1"; axios.get(url) .then((response) => response) .then((responseObject) => console.log(responseObject.data)) .catch((err) => console.log(err)); 


With async/await 


내부적으로 우리는 여전히 약속을 사용하고 있습니다. Async / await는 코드를 훨씬 더 깔끔하게 만듭니다.


const axios = require("axios"); const getData = async (url) => { const res = await axios.get(url); const json = await res.data; console.log(json); }; const url = "https://jsonplaceholder.typicode.com/todos/1"; getData(url); 


Making multiple request simultaneously 


const axios = require("axios"); const getData = async (url, id) => { console.log("Making request to id ", id); const res = await axios.get(url + id); const json = await res.data; console.log(json); return json; }; const url = "https://jsonplaceholder.typicode.com/posts/"; const ids = [1, 2, 3, 4, 5, 6, 7]; axios .all(ids.map((id) => getData(url, id))) .then( (res) => console.log(res) // Array of all the json data //[ {userId:1} , {userId:2} , {userId:3}...........] ) .catch((err) => console.log(err)); 


매개 변수 전달 


URL에 추가 


const getData = async (url) => { const res = await axios.get(url); const json = await res.data; console.log(json); }; const url = "https://jsonplaceholder.typicode.com/posts?userId=1"; getData(url); 


params 객체 만들기 


const getData = async (url,params) => { const res = await axios.get(url,{ params: params }); const json = await res.data; console.log(json); }; const url = "https://jsonplaceholder.typicode.com/posts"; const params = { userId: 1 } getData(url,params); 


헤더 객체 전달 


이는 사용중인 API에 인증이 필요한 경우 유용합니다. Cats as a Service API로 작업 할 것입니다.


.env 파일에 저장된 env 변수 로드 


npm을 사용하여 'dotenv'를 설치해야 합니다.


npm install dotenv 


아래 코드 조각은 환경 변수를 읽습니다.


require("dotenv").config(); const CAT_API_KEY = process.env.API_KEY; 


API에 요청 해 보겠습니다.


const getData = async (url,headers) => { const res = await axios.get(url,{ headers: headers }); const json = await res.data; console.log(json); }; const url = "https://api.thecatapi.com/v1/breeds"; const headers = { "x-api-key": CAT_API_KEY, }; getData(url,headers); 


요청을 할 때 객체를 만들고 그 안에 헤더 객체를 저장합니다.


오류 처리 


Cat의 API가 아닌 존재하지 않는 엔드 포인트에 요청을 만들어 보겠습니다.


then..catch로 처리 


axios .get(url, { headers: headers, }) .then((res) => res) .then((responseObject) => console.log(responseObject.data)) .catch((err) => console.log(err)); 


async / await 및 try… catch 처리 


const getData = async (url, headers) => { try { const res = await axios.get(url, { headers: headers, }); } catch (err) { console.log(err); } }; 


포스트 요청하기 


const postData = async (url, data) => { const res = await axios.post(url, { ...data, }); const json = await res.data; console.log(json); }; const url = "https://jsonplaceholder.typicode.com/posts"; const data = { title: "test Data", body: "this is a test post request", userId: 120, }; postData(url, data); 


응답 개체 


const getData = async (url) => { const res = await axios.get(url); const json = await res.data console.log(json); // The JSON data console.log(res.status) // 200 console.log(res.statusText) // OK /** * The below provide more info about your request * such as url, request type, redirects, protocols etc */ console.log(res.headers) console.log(res.config) console.log(res.request) }; 


https://www.realpythonproject.com/a-cheat-sheet-for-javascripts-axios/



댓글목록 0

등록된 댓글이 없습니다.

웹학교 로고

온라인 코딩학교

코리아뉴스 2001 - , All right reserved.