Nodejs 와 브라우저에서 HTTP 통신하기 (axios)

axios 는 Nodejs 와 웹브라우저 에서 사용할 수 있는 Promise 방식의 HTTP 클라이언트 이다.

axios

사용량
weekly downloads 가 1천만이 넘는다
axios

설치

1
2
3
4
5
6
7
8
9
10
#npm
npm install axios
#bower
bower install axios
#yarn
yarn add axios
#jsDelivr CDN
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
#unpkg CDN
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

사용예

Get

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const axios = require('axios');

// 일반적으로 사용할 때
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});

// 옵션을 추가해서 사용할 때
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});

// async/await 방식으로 사용할 때
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}

Post

1
2
3
4
5
6
7
8
9
10
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

multi requests

1
2
3
4
5
6
7
8
9
10
11
12
13
function getUserAccount() {
return axios.get('/user/12345');
}

function getUserPermissions() {
return axios.get('/user/12345/permissions');
}

Promise.all([getUserAccount(), getUserPermissions()])
.then(function (results) {
const acct = results[0];
const perm = results[1];
});

image file 을 받는 방법

1
2
3
4
5
6
7
8
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});

Request Config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
{
url: '/user',
method: 'get', // default
baseURL: 'https://some-domain.com/api/',
transformRequest: [function (data, headers) {
// Do whatever you want to transform the data
return data;
}],

transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],

// `headers` are custom headers to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'},

params: {
ID: 12345
},

paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},

data: {
firstName: 'Fred'
},

data: 'Country=Brasil&City=Belo Horizonte',
timeout: 1000, // default is `0` (no timeout)
withCredentials: false, // default
adapter: function (config) {
/* ... */
},

auth: {
username: 'janedoe',
password: 's00pers3cret'
},

responseType: 'json', // default
responseEncoding: 'utf8', // default
xsrfCookieName: 'XSRF-TOKEN', // default
xsrfHeaderName: 'X-XSRF-TOKEN', // default
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},

onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},

maxContentLength: 2000,
maxBodyLength: 2000,
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
maxRedirects: 5, // default
socketPath: null, // default
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),

proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},

cancelToken: new CancelToken(function (cancel) {
}),

decompress: true // default

}

Response Schema

1
2
3
4
5
6
7
8
{
data: {},
status: 200,
statusText: 'OK',
headers: {},
config: {},
request: {}
}

Config

Global axios defaults

1
2
3
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

instance defaults

1
2
3
4
5
6
const instance = axios.create({
baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

Interceptors

1
2
3
4
5
6
7
8
9
10
11
12
13
// Add a request interceptor
axios.interceptors.request.use(function (config) {
return config;
}, function (error) {
return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
return Promise.reject(error);
});

Errors 처리

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});