๐ก Node.js๋ฅผ ์ํ Promise API๋ฅผ ํ์ฉํ๋ HTTP ๋น๋๊ธฐ ํต์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
๐ก ์ค์น๊ฐ ๋ณ๋ ํ์
๐ก ์๋์ผ๋ก JSON๋ฐ์ดํฐ๋ก ๋ณํ๋จ
npm install axios
๐ fetch
//Promise
fetch(URL, {method : 'GET'})
.then((response) => response.json())
.then((json) => return json)
.catch((error) => console.log(error));
//Async & await
async function x() {
const response = await fetch(URL, {method : 'GET'});
const data = await response.json();
return data;
}
x();
๐ axios
//Promise
import axios from 'axios';
axios
.get(URL)
.then((response) => {
const { data } = response;
return data;
})
.catch((error) => console.log(error));
//Async & await
async function x(){
const response = await axios.get(URL);
const { data } = response;
return data;
}
x();
๐ fetch
//Promise
fetch(URL, {
method : 'POST',
headers : {
'Content-Type' : 'application/json',
},
body : JSON.stringify({ name : 'a', number : 1 }),
})
.then((response) => response.json())
.then((json) => return json)
.catch((error) => console.log(error));
//Async & await
async function x() {
const response = await fetch(URL, {
method : 'POST',
headers : {
'Content-Type' : 'application/json',
},
body : JSON.stringify({ name : 'a', number : 1 }),
});
const data = await response.json();
return data;
}
x();
๐ axios
//Promise
import axios from 'axios';
axios
.post(URL, {
name : 'a', number : 1
})
.then((response) => {
const { data } = response;
return data;
})
.catch((error) => console.log(error));
//Async & await
async function x() {
const response = await axios.post(URL, {
name : 'a', number : 1
});
const data = await response.json();
return data;
}
x();