API 우선 인증, 승인 및 사기 방지 웹사이트 | 문서 | Node.js | 우리는 하나의 공통 목적을 가지고 있습니다: 귀하에게 필요한 금융 도구, 자원 및 정보를 제공하는 것입니다. www.principal.com | 안녕하세요 데스코프입니다! 우리는 앱 개발자를 위한 인증 공간을 구축하고 있으며... 웹사이트 | 문서 | 지역 사회 |
Buzzoid에서는 단 몇 번의 클릭만으로 빠르고 안전하며 쉽게 인스타그램 팔로워를 구매할 수 있습니다. 비율... buzzoid.com | Famety에서는 단 몇 번의 클릭만으로 빠르고 안전하며 쉽게 소셜 미디어를 팔로우할 수 있습니다. www.famety.com | 인스타그램 좋아요 구매 poprey.com |
? 후원자가 되세요 | ? 후원자가 되세요 | ? 후원자가 되세요 |
브라우저 및 node.js용 Promise 기반 HTTP 클라이언트
웹사이트 • 문서
multipart/form-data
및 x-www-form-urlencoded
본문 인코딩으로의 자동 데이터 객체 직렬화최신 ✔ | 최신 ✔ | 최신 ✔ | 최신 ✔ | 최신 ✔ |
npm 사용:
$ npm install axios
정자 사용:
$ bower install axios
원사 사용:
$ yarn add axios
pnpm 사용:
$ pnpm add axios
패키지가 설치되면 import
또는 require
접근 방식을 사용하여 라이브러리를 가져올 수 있습니다.
import axios , { isCancel , AxiosError } from 'axios' ;
명명된 내보내기는 Axios 팩토리에서 다시 내보내기이므로 기본 내보내기를 사용할 수도 있습니다.
import axios from 'axios' ;
console . log ( axios . isCancel ( 'something' ) ) ;
가져오기에 require
사용하는 경우 기본 내보내기만 사용할 수 있습니다 .
const axios = require ( 'axios' ) ;
console . log ( axios . isCancel ( 'something' ) ) ;
일부 번들러 및 일부 ES6 linter의 경우 다음을 수행해야 할 수 있습니다.
import { default as axios } from 'axios' ;
모듈을 사용자 정의 또는 레거시 환경으로 가져오려고 할 때 문제가 발생한 경우 모듈 패키지를 직접 가져올 수 있습니다.
const axios = require ( 'axios/dist/browser/axios.cjs' ) ; // browser commonJS bundle (ES2017)
// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)
jsDelivr CDN 사용(ES5 UMD 브라우저 모듈):
< script src =" https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js " > </ script >
unpkg CDN 사용:
< script src =" https://unpkg.com/[email protected]/dist/axios.min.js " > </ script >
참고 : CommonJS 사용법
require()
와 함께 CommonJS 가져오기를 사용하는 동안 TypeScript 유형 지정(intellisense/자동 완성용)을 얻으려면 다음 접근 방식을 사용하십시오.
import axios from 'axios' ;
//const axios = require('axios'); // legacy way
// Make a request for a user with a given ID
axios . get ( '/user?ID=12345' )
. then ( function ( response ) {
// handle success
console . log ( response ) ;
} )
. catch ( function ( error ) {
// handle error
console . log ( error ) ;
} )
. finally ( function ( ) {
// always executed
} ) ;
// Optionally the request above could also be done as
axios . get ( '/user' , {
params : {
ID : 12345
}
} )
. then ( function ( response ) {
console . log ( response ) ;
} )
. catch ( function ( error ) {
console . log ( error ) ;
} )
. finally ( function ( ) {
// always executed
} ) ;
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser ( ) {
try {
const response = await axios . get ( '/user?ID=12345' ) ;
console . log ( response ) ;
} catch ( error ) {
console . error ( error ) ;
}
}
참고 :
async/await
ECMAScript 2017의 일부이며 Internet Explorer 및 이전 브라우저에서는 지원되지 않으므로 주의해서 사용하세요.
POST
요청 수행
axios . post ( '/user' , {
firstName : 'Fred' ,
lastName : 'Flintstone'
} )
. then ( function ( response ) {
console . log ( response ) ;
} )
. catch ( function ( error ) {
console . log ( error ) ;
} ) ;
여러 동시 요청 수행
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 ] ;
} ) ;
관련 구성을 axios
에 전달하여 요청할 수 있습니다.
// Send a POST request
axios ( {
method : 'post' ,
url : '/user/12345' ,
data : {
firstName : 'Fred' ,
lastName : 'Flintstone'
}
} ) ;
// GET request for remote image in node.js
axios ( {
method : 'get' ,
url : 'https://bit.ly/2mTM3nY' ,
responseType : 'stream'
} )
. then ( function ( response ) {
response . data . pipe ( fs . createWriteStream ( 'ada_lovelace.jpg' ) )
} ) ;
// Send a GET request (default method)
axios ( '/user/12345' ) ;
편의를 위해 모든 일반적인 요청 방법에 별칭이 제공되었습니다.
별칭 메서드를 사용하는 경우 url
, method
및 data
속성을 config에서 지정할 필요가 없습니다.
아래 기능을 대체하려면 Promise.all
사용하세요.
동시 요청을 처리하기 위한 도우미 함수입니다.
axios.all(반복 가능) axios.spread(콜백)
사용자 정의 구성을 사용하여 새로운 axios 인스턴스를 생성할 수 있습니다.
const instance = axios . create ( {
baseURL : 'https://some-domain.com/api/' ,
timeout : 1000 ,
headers : { 'X-Custom-Header' : 'foobar' }
} ) ;
사용 가능한 인스턴스 메서드는 다음과 같습니다. 지정된 구성이 인스턴스 구성과 병합됩니다.
요청에 사용할 수 있는 구성 옵션은 다음과 같습니다. url
만 필수입니다. method
지정되지 않은 경우 요청은 기본적으로 GET
으로 설정됩니다.
{
// `url` is the server URL that will be used for the request
url : '/user' ,
// `method` is the request method to be used when making the request
method : 'get' , // default
// `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to methods of that instance.
baseURL : 'https://some-domain.com/api/' ,
// `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
// FormData or Stream
// You may modify the headers object.
transformRequest : [ function ( data , headers ) {
// Do whatever you want to transform the data
return data ;
} ] ,
// `transformResponse` allows changes to the response data to be made before
// it is passed to then/catch
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` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
params : {
ID : 12345
} ,
// `paramsSerializer` is an optional config that allows you to customize serializing `params`.
paramsSerializer : {
//Custom encoder function which sends key/value pairs in an iterative fashion.
encode ?: ( param : string ) : string => { /* Do custom operations here and return transformed string */ } ,
// Custom serializer function for the entire parameter. Allows user to mimic pre 1.x behaviour.
serialize ?: ( params : Record < string , any > , options ?: ParamsSerializerOptions ) ,
//Configuration for formatting array indexes in the params.
indexes : false // Three available options: (1) indexes: null (leads to no brackets), (2) (default) indexes: false (leads to empty brackets), (3) indexes: true (leads to brackets with indexes).
} ,
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and '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, FormData (form-data package)
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` specifies the number of milliseconds before the request times out.
// If the request takes longer than `timeout`, the request will be aborted.
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 ) {
/* ... */
} ,
// Also, you can set the name of the built-in adapter, or provide an array with their names
// to choose the first available in the environment
adapter : 'xhr' // 'fetch' | 'http' | ['xhr', 'http', 'fetch']
// `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` indicates the type of data that the server will respond with
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
// browser only: 'blob'
responseType : 'json' , // default
// `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
// Note: Ignored for `responseType` of 'stream' or client-side requests
// options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url',
// 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8',
// 'utf8', 'UTF8', 'utf16le', 'UTF16LE'
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
// `undefined` (default) - set XSRF header only for the same origin requests
withXSRFToken : boolean | undefined | ( ( config : InternalAxiosRequestConfig ) => boolean | undefined ) ,
// `onUploadProgress` allows handling of progress events for uploads
// browser & node.js
onUploadProgress : function ( { loaded , total , progress , bytes , estimated , rate , upload = true } ) {
// Do whatever you want with the Axios progress event
} ,
// `onDownloadProgress` allows handling of progress events for downloads
// browser & node.js
onDownloadProgress : function ( { loaded , total , progress , bytes , estimated , rate , download = true } ) {
// Do whatever you want with the Axios progress event
} ,
// `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
maxContentLength : 2000 ,
// `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
maxBodyLength : 2000 ,
// `validateStatus` defines whether to resolve or reject the promise for a given
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
// or `undefined`), the promise will be resolved; otherwise, the promise will be
// rejected.
validateStatus : function ( status ) {
return status >= 200 && status < 300 ; // default
} ,
// `maxRedirects` defines the maximum number of redirects to follow in node.js.
// If set to 0, no redirects will be followed.
maxRedirects : 21 , // default
// `beforeRedirect` defines a function that will be called before redirect.
// Use this to adjust the request options upon redirecting,
// to inspect the latest response headers,
// or to cancel the request by throwing an error
// If maxRedirects is set to 0, `beforeRedirect` is not used.
beforeRedirect : ( options , { headers } ) = > {
if ( options . hostname === "example.com" ) {
options . auth = "user:password" ;
}
} ,
// `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
// `transport` determines the transport method that will be used to make the request. If defined, it will be used. Otherwise, if `maxRedirects` is 0, the default `http` or `https` library will be used, depending on the protocol specified in `protocol`. Otherwise, the `httpFollow` or `httpsFollow` library will be used, again depending on the protocol, which can handle redirects.
transport : undefined , // 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' ,
// hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
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 ) {
} ) ,
// an alternative way to cancel Axios requests using AbortController
signal : new AbortController ( ) . signal ,
// `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
// `insecureHTTPParser` boolean.
// Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
// This may allow interoperability with non-conformant HTTP implementations.
// Using the insecure parser should be avoided.
// see options https://nodejs.org/dist/latest-v12.x/docs/ap