-
ky와 got으로 API 호출하기JavaScript 2022. 11. 15. 08:59
- ky는 브라우저, got은 node.js 환경에서 사용된다.
- axios에 비해서 가볍다. (다만, axios는 서버/클라이언트 모두 호환된다.)
import React, {useEffect, useState} from 'react'; import ky from 'ky'; export default function App() { const [data, setData] = useState(null); useEffect(() => { ky.get('url 주소').then((response) => (setData(response))) }, []); return ( <div> <h1>{JSON.stringify(data)}</h1> </div> ); }- React에서 ky를 사용하여 post 요청을 보낼 수 있다.
- json 객체 내부에 json 데이터를 담아 보낼 수 있고, response를 json 메서드를 통해서 json으로 변환할 수 있다.
import ky from "ky"; const HttpRequestWithKy = () => { const handlePostClick = async () => { const response = await ky .post("http://localhost:8080/login", { json: { email: "aaa@aaa.aaa", password: "aaa111!!!", }, }) .json(); alert(JSON.stringify(response)); }; return ( <div> <h1>KY Test</h1> <div> <h3>POST TEST</h3> <button onClick={handlePostClick}>POST REQUEST</button> </div> </div> ); }; export default HttpRequestWithKy;- got을 import해오기 위해서 node 프로젝트에서는 package.json에 "type": "module"을 추가해준다.
import got from 'got'; const {data} = await got.get('url 주소'); console.log(data);- 두 라이브러리는 fetch처럼 .json() 메서드를 사용하여 response를 json 형태로 변환할 수 있다.
- 기본적으로 ky와 got의 사용법은 유사한 것 같다.
- 차이점은 ky는 브라우저 환경에서 주로 사용되고 got은 node 환경에서 사용되는 점 같다.
🍙 got은 브라우저 환경에서 지원되지 않는 라이브러리이다.
https://github.com/sindresorhus/ky
GitHub - sindresorhus/ky: 🌳 Tiny & elegant JavaScript HTTP client based on the browser Fetch API
🌳 Tiny & elegant JavaScript HTTP client based on the browser Fetch API - GitHub - sindresorhus/ky: 🌳 Tiny & elegant JavaScript HTTP client based on the browser Fetch API
github.com
https://github.com/sindresorhus/got
GitHub - sindresorhus/got: 🌐 Human-friendly and powerful HTTP request library for Node.js
🌐 Human-friendly and powerful HTTP request library for Node.js - GitHub - sindresorhus/got: 🌐 Human-friendly and powerful HTTP request library for Node.js
github.com
'JavaScript' 카테고리의 다른 글
javascript 정렬 알고리즘 (3) 2022.11.17 javascript 순열과 조합 알고리즘 (0) 2022.11.16 상태관리 라이브러리 Redux (0) 2022.11.12 text-shadow 적용하기 (0) 2022.11.03 간단한 calc() 사용하는 법 (0) 2022.11.01