axios github url: https://github.com/axios/axios
axios는 브라우저에서 XMLHttpRequests 를 만들 수 있는 모듈이다. promise도 지원한다.
axios 설치:
npm install axios --no-audit
그냥 npm install axios를 하면 되지만, windows powershell에서 --no-audit을 붙이지 않고 설치하려하면 취약점이 있다며 설치되지 않았다.
axios import:
commonJS방식
const axios = require('axios').default;
ES6방식
import axios from 'axios';
axios 메소드: request에서 method를 명시하지 않고 메소드로도 사용할 수 있다.
axios.request(config)
axios.get(url[, config])
axios.post(url[, data[, config]])
request config: object형식으로 구성되어있다.
{
// request할 url이다.
url: '/user',
// request method이다.
method: 'get', // default
// url이 상대경로일 때 사용된다.
baseURL: 'https://some-domain.com/api',
// `transformRequest`는 서버에 데이터를 보내기 전에 바꾸기가 가능하다.
// 'PUT', 'POST', 'PATCH', 'DELETE' 메소드에서만 가능하다.
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
// FormData or Stream
// headers object를 변경하고싶다면
transformRequest: [function (data, headers) {
// 데이터를 변경시키기 위해 하고싶은 코드
return data;
}],
// `transformResponse`는 response데이터가 then/catch되기 전에 변경할 수 있다.
transformResponse: [function (data) {
// 데이터를 변경시키기 위해 하고싶은 코드
return data;
}],
// `headers` header를 커스터마이징한다.
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
// NOTE: params that are null or undefined are not rendered in the URL.
params: {
ID: 12345
},
// `paramsSerializer` is an optional function in charge of serializing `params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data` request body에 보내지는 데이터다.
// 'PUT', 'POST', 'DELETE', 'PATCH'메소드에서 사용 가능하다.
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
},
// syntax alternative to send data into the body
// method post
// only the value is sent, not the key
data: 'Country=Brasil&City=Belo Horizonte',
// `timeout`보다 request가 길어지면 중단시킨다. ms단위.
timeout: 1000, // default is `0` (no timeout)
// `withCredentials` indicates whether or not cross-site Access-Control requests
// should be made using credentials
withCredentials: false, // default
// `adapter` allows custom handling of requests which makes testing easier.
// Return a promise and supply a valid response (see lib/adapters/README.md).
adapter: function (config) {
/* ... */
},
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an `Authorization` header, overwriting any existing
// `Authorization` custom headers you have set using `headers`.
// Please note that only HTTP Basic auth is configurable through this parameter.
// For Bearer tokens and such, use `Authorization` custom headers instead.
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType`는 서버가 보내는 데이터의 타입을 나타낸다.
// 'arraybuffer', 'document', 'json', 'text', 'stream'가 가능하다.
responseType: 'json', // default
responseType: 'steram', //영상이나 이미지 다운
// `responseEncoding`는 response를 디코드할 인코딩을 나타낸다.(Node.js only)
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default
// `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress` allows handling of progress events for uploads
// browser only
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `onDownloadProgress` allows handling of progress events for downloads
// browser only
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `maxContentLength`는 response 콘텐트 최대 사이즈를 바이트로 정의한다.allowed in node.js
maxContentLength: 2000,
// `maxBodyLength`는 request 콘텐트 최대 사이즈를 바이트로 정의한다.(Node only option)
maxBodyLength: 2000,
// `validateStatus`는 http response status code로 promise가 resolve할지 reject할지 결정한다.
// `validateStatus`가 `true`를 반환하면 promise가 resolved될것이고, 반대면 rejected될것이다.
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects`는 redirect될 최대 수를 정한다.
// 0이면 redirect되지 않는다.
maxRedirects: 5, // default
// `socketPath` defines a UNIX Socket to be used in node.js.
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
// Only either `socketPath` or `proxy` can be specified.
// If both are specified, `socketPath` is used.
socketPath: null, // default
// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
// and https requests, respectively, in node.js. This allows options to be added like
// `keepAlive` that are not enabled by default.
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// `proxy` defines the hostname, port, and protocol of the proxy server.
// You can also define your proxy using the conventional `http_proxy` and
// `https_proxy` environment variables. If you are using environment variables
// for your proxy configuration, you can also define a `no_proxy` environment
// variable as a comma-separated list of domains that should not be proxied.
// Use `false` to disable proxies, ignoring environment variables.
// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
// supplies credentials.
// This will set an `Proxy-Authorization` header, overwriting any existing
// `Proxy-Authorization` custom headers you have set using `headers`.
// If the proxy server uses HTTPS, then you must set the protocol to `https`.
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` specifies a cancel token that can be used to cancel the request
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
}),
// `decompress` indicates whether or not the response body should be decompressed
// automatically. If set to `true` will also remove the 'content-encoding' header
// from the responses objects of all decompressed responses
// - Node only (XHR cannot turn off decompression)
decompress: true // default
}
response 구조:
{
// 서버에서 전송된 데이터다.
data: {},
// 서버에서 응답온 상태코드이다.
status: 200,
// 서버에서 응답온 상태텍스트이다.
statusText: 'OK',
// 서버에서 응답한 http헤더이다. 모든헤더의 이름은 lowercase이고 중괄호 표기로 접근 가능하다.
// Example: `response.headers['content-type']`
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance in the browser
request: {}
}
예시:
const axios = require('axios').default;
axios.request({
method: 'post', //post, get가능
url: 'https://www.google.co.kr/', //url을 넣으면 된다.
// 헤더를 커스텀 할 수 있다.
headers: {'X-Requested-With': 'XMLHttpRequest'},
// timeout보다 오랜 시간이 걸리면 요청을 중단한다.
timeout: 1000,
// 'arraybuffer', 'document', 'json', 'text', 'stream'가 있다.
responseType: 'json', // 기본은 json이다.
data: {
firstName: 'Fred',
lastName: 'Flintstone'
} //method post일 때 사용
})
.then(function (response) { //성공했을 때 함수
console.log(response.headers);
console.log(response.data);
})
.catch(function (error) { //실패했을 때 함수
console.log(error);
});
async/await사용
const axios = require('axios').default;
async function main() {
try {
let response = await axios.get('https://www.google.co.kr/', {
responseType: 'json',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0',
}
})
console.log(response.data);
} catch (error) {
console.log(error);
}
}
main();
한글이 보이지 않는다면 request config의 responseEncoding:'utf8'로 해보자.
그래도 인코딩이 깨진다면, responseEncoding: "binary"를 설정한 후, iconv똔는 iconv-lite로 한글처리하면 된다.
'Node.js' 카테고리의 다른 글
https 모듈로 crawling하기 (0) | 2022.08.04 |
---|---|
package.json (0) | 2022.07.21 |
nodejs 외부 js파일(모듈) 함수 호출하기 (0) | 2022.07.20 |
nodejs console 입력받기 (readline, readline-sync module) (0) | 2022.07.20 |
hello world! (0) | 2022.07.15 |