Axios
ํ์ต ํค์๋
Axios
Ajax
Fetch vs Axios
์ฌ์ฉ๋ฒ
Node.js์ ๋ธ๋ผ์ฐ์ ๋ฅผ ์ํ Promise ๊ธฐ๋ฐ HTTP ํด๋ผ์ด์ธํธ (HTTP ๋น๋๊ธฐ ํต์ ํด๋ผ์ด์ธํธ)
ํน์ง
๋ธ๋ผ์ฐ์ ๋ฅผ ์ํด XMLHttpRequests ์์ฑ
node.js๋ฅผ ์ํด http ์์ฒญ ์์ฑ
Promise API๋ฅผ ์ง์
์์ฒญ ๋ฐ ์๋ต ์ธํฐ์ ํธ
์์ฒญ ๋ฐ ์๋ต ๋ฐ์ดํฐ ๋ณํ
์์ฒญ ์ทจ์
โ JSON ๋ฐ์ดํฐ ์๋ ๋ณํ
XSRF๋ฅผ ๋ง๊ธฐ์ํ ํด๋ผ์ด์ธํธ ์ฌ์ด๋ ์ง์
๐ค ์ Axios๋ฅผ ์ฌ์ฉํ๋ ์ด์ ?
์ฐ์ React๋ ๋น๋๊ธฐ ํต์ ์ ์ํ HTTP Client๋ฅผ ๊ตฌํํ๊ธฐ ์ํ ๊ธฐ๋ฅ์ด ์ ๊ณต ๋์ง ์๋๋ค. ๋ฐ๋ผ์ React Ajax๋ฅผ ๊ตฌํํ๊ธฐ ์ํด์๋ JavaScript ๋ด์ฅ ๊ฐ์ฒด์ธ XMLRequest๋ฅผ ์ฌ์ฉํ๊ฑฐ๋ , ๋ค๋ฅธ HTTP Client๋ฅผ ์ฌ์ฉ ํด์ผ ํ๋ค.
๋ธ๋ผ์ฐ์ ๊ฐ ์ ๊ณตํ๋ Fetch API๋ฅผ ์ฌ์ฉํด๋ ๋์ง๋ง ๋ณด๋ค ๋ ๋ง์ ๊ธฐ๋ฅ์ ์ ๊ณตํด์ ์ฌ๋๋ค์ ์ ํธ๋๊ฐ ๋์ ๋ง์ด ์ฌ์ฉ๋๋ค.
๐ Ajax
๋ธ๋ผ์ฐ์ ๊ฐ ๊ฐ๊ณ ์๋ XMLHttpRequest ๊ฐ์ฒด๋ฅผ ์ด์ฉํด์ ์ ์ฒด ํ์ด์ง๋ฅผ ์๋ก๊ณ ์นจ ํ์ง ์์๋ ํ์ด์ง์ ์ผ๋ถ๋ถ๋ง์ ์ํ ๋ฐ์ดํฐ๋ฅผ ๋ก๋ํ๋ ๊ธฐ๋ฒ
JavaScript๋ฅผ ์ฌ์ฉํ ๋น๋๊ธฐ ํต์ , ํด๋ผ์ด์ธํธ์ ์๋ฒ ๊ฐ์ XML ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ๋ ๊ธฐ์
Fetch vs Axios
์ ํ
๋ธ๋ผ์ฐ์ ๋นํธ์ธ
์จ๋ํํฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
๋ฐ์ดํฐ
data ์์ฑ์ ์ฌ์ฉ
body ์์ฑ์ ์ฌ์ฉ
๋ฐ์ดํฐ ํ์
data๋ object๋ฅผ ํฌํจํ๋ค.
body๋ ๋ฌธ์์ดํ ๋์ด์๋ค.
์๋ต
status๊ฐ 200์ด๊ณ statusText๊ฐ โOKโ์ด๋ฉด ์ฑ๊ณต์ด๋ค.
์๋ต๊ฐ์ฒด๊ฐ ok ์์ฑ์ ํฌํจํ๋ฉด ์ฑ๊ณต์ด๋ค.
json
์๋์ผ๋ก JSON๋ฐ์ดํฐ ํ์์ผ๋ก ๋ณํ
.json()๋ฉ์๋๋ฅผ ์ฌ์ฉ
์์ฒญ ์ปค์คํ
์์ฒญ์ ์ทจ์ํ ์ ์๊ณ ํ์์์์ ๊ฑธ ์ ์๋ค.
ํด๋น ๊ธฐ๋ฅ ์กด์ฌ ํ์ง์์
HTTP ์์ฒญ
HTTP ์์ฒญ์ ๊ฐ๋ก์ฑ์ ์์
๊ธฐ๋ณธ์ ์ผ๋ก ์ ๊ณตํ์ง ์์
download
download ์งํ์ ๋ํด ๊ธฐ๋ณธ์ ์ธ ์ง์์ ํจ
์ง์ํ์ง ์์
์ง์ ๋ธ๋ผ์ฐ์
์ข ๋ ๋ง์ ๋ธ๋ผ์ฐ์ ์ ์ง์๋จ
Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+
โ๏ธ ์ค์น ๋ฐ ์ฌ์ฉ๋ฒ
npm install axios
get
์์ฒญ
get
์์ฒญ// Promise chaining
axios
.get('/user', {params : { ID : 12345 },
})
.then((response) => console.log(response))
.catch((error) => console.log(error) )
.then(() => console.log('done'));
// async await
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
return response.data;
} catch (error) {
console.log(error);
}
}
post
์์ฒญ
post
์์ฒญ// Promise chaining
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// async await
async function postUser() {
try {
const response = await axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
});
return response.data;
} catch (error) {
console.log(error);
}
}
๐ ์ฐธ๊ณ
Last updated