Promise API๋ฅผ ํ์ฉํ๋ HTTP ๋น๋๊ธฐ ํต์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
Using npm:
$ npm install axios
Using bower:
$ bower install axios
Using yarn:
$ yarn add axios
Using jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Using unpkg CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
import axios from 'axios'
axios({
url: 'URL',
method: 'get|post|put|patch|delete ๋ฑ..',
data: {
ํค: '๊ฐ',
ํค: '๊ฐ',
}
})
.then((response) => {
// ์ฑ๊ณต์
})
.catch((error) => {
// ์คํจ์
})
.finally(() => {
// ํญ์
})
| ์์ฒญ | ์ค๋ช |
|---|---|
| method | ์์ฒญ ๋ฐฉ์ (๋ฏธ์ง์ ์ get) |
| url | ์๋ฒ ์ฃผ์ |
| baseURL | url์ด ์๋๊ฒฝ๋ก์ผ ๋, url ์์ ๋ถ๋ ์ฃผ์ |
| header | ์์ฒญ ํค๋ |
| data | body์ ์ค์ ๋ฐ์ดํฐ |
| responseType | ์๋ฒ๊ฐ ์๋ตํด์ฃผ๋ ๋ฐ์ดํฐ์ ํ์ (json, text ๋ฑ) |
| withCredentials | cross-site access-control ์์ฒญ ํ์ฉ ์ ๋ฌด (true์ผ ๋ cross-origin์ผ๋ก ์ฟ ํค๊ฐ ์ ๋ฌ) |
๊ธฐ๋ณธ ํ์์๋ ๊ฐ์ฒด ์ต์
์ด ๋๋ฌด ๋ง์
์ด๋ฅผ ์ค์ผ ์ ์๋๋ก Axios ๋จ์ถ ๋ฉ์๋๋ฅผ ์ ๊ณตํ๋ค.
GET : axios.get(url[, config])
POST : axios.post(url, data[, config])
PUT : axios.put(url, data[, config])
DELETE : axios.delete(url[, config])
๊ทธ๋ฅ URL์ ์์ฒญ์ ๋ณด๋ด๊ฑฐ๋, ํ๋ผ๋ฏธํฐ์ ๋ฐ์ดํฐ๋ฅผ ํฌํจ์์ผ์ ๋ณด๋ผ ์ ์๋ค.
const axios = require('axios');
axios.get('url', {
params: {
ID: 12345
}
})
.then((response) => {
// ์ฑ๊ณต์
})
...
// ๋๋
axios.get('/user?ID=12345')
...
๋ฐ์ดํฐ๋ฅผ Message Body์ ํฌํจ์์ผ ๋ณด๋ธ๋ค.
axios.post('url', {
ํค: '๊ฐ',
ํค: '๊ฐ',
})
...
GET๊ณผ ๊ฐ์ด ๊ทธ๋ฅ URL๋ก ์์ฒญ์ ๋ณด๋ด๊ฑฐ๋,
ํ๋ผ๋ฏธํฐ์ ๋ฐ์ดํฐ๋ฅผ ํฌํจ์์ผ์ ๋ณด๋ผ ์ ์๋ค.
axios.delete('url')
...
// ๋๋
axios.delete('url',{
data: {
ํค: ๊ฐ,
ํค: ๊ฐ,
ํค: ๊ฐ,
}
})
const ์์ฒญ1 = () => {
return axios.get('์์ฒญurl1');
}
const ์์ฒญ2 = () => {
return axios.get('์์ฒญurl2');
}
axios.all([์์ฒญ1(), ์์ฒญ2(), โฆ])
.then(() => {
const ๊ฒฐ๊ณผ1 = result[0];
const ๊ฒฐ๊ณผ2 = result[2];
โฆ
})
์๋ฒ๋ก๋ถํฐ ์๋ต ๋ฐ์ response ๊ฐ์ฒด๋ ์๋์ ๊ฐ์ด ๊ตฌ์ฑ๋์ด ์๋ค.
{
data: {}, // ์๋ต ๋ฐ์ดํฐ
status: 200, // HTTP ์ํ ์ฝ๋
statusText: 'OK', // HTTP ์ํ ๋ฉ์์ง
headers: {}, // ํค๋
config: {}, // ์์ฒญ์ ์ํด `axios`๊ฐ ์ ๊ณตํ๋ ๊ตฌ์ฑ
request: {}
// `request`๋ ์๋ต์ ์์ฑํ ์์ฒญ
// ๋ธ๋ผ์ฐ์ : XMLHttpRequest ์ธ์คํด์ค
// Node.js: ClientRequest ์ธ์คํด์ค(๋ฆฌ๋๋ ์
)
}