웹 프론트엔드 CSS 튜토리얼 axios가 Promise를 기반으로 HTTP 요청 클라이언트를 만드는 방법

axios가 Promise를 기반으로 HTTP 요청 클라이언트를 만드는 방법

Mar 09, 2018 pm 05:09 PM
axios http promise

이번에는 axios가 Promise 기반 HTTP 요청 클라이언트를 어떻게 사용하는지 보여드리겠습니다. Axios Promise 기반 HTTP 요청 클라이언트의 Notes는 무엇인가요?

axios

브라우저와 node.js 모두에서 사용할 수 있는 Promise 기반 HTTP 요청 클라이언트

Features

브라우저에서 XMLHttpRequests 요청 보내기

node.js에서 http 요청 보내기

PromiseAPI 지원

요청 및 응답 차단

요청 및 응답 데이터 변환

JSON 데이터 자동 변환

npm으로부터 보안을 보호하기 위한 클라이언트 지원:

$ bower install axios
로그인 후 복사

GET 요청 보내기

$ npm install axios
로그인 후 복사

POST 요청 보내기

// Make a request for a user with a given IDaxios.get('/user?ID=12345').then(function(response){console.log(response);}).catch(function(response){console.log(response);});
// Optionally the request above could also be done asaxios.get('/user',{params:{ID:12345}}).then(function(response){console.log(response);}).catch(function(response){console.log(response);});
로그인 후 복사

여러 동시 요청 보내기

axios.post('/user',{firstName:'Fred',lastName:'Flintstone'}).then(function(response){console.log(response);}).catch(function(response){console.log(response);});
로그인 후 복사

axios API

해당 매개변수를 axios에 전달하여 요청을 맞춤 설정할 수 있습니다.

functiongetUserAccount(){returnaxios.get('/user/12345');}functiongetUserPermissions(){returnaxios.get('/user/12345/permissions');}axios.all([getUserAccount(),getUserPermissions()]).then(axios.spread(function(acct,perms){// Both requests are now complete}));
로그인 후 복사


요청 방법

alias


편의를 위해 지원되는 모든 요청 방법에 별칭을 제공합니다

axios(config)
// Send a POST requestaxios({method:'post',url:'/user/12345',data:{firstName:'Fred',lastName:'Flintstone'}});
axios(url[, config])
// Sned a GET request (default method)axios('/user/12345');
로그인 후 복사

참고

별칭 메서드를 사용하는 경우 url, 메서드 및 데이터 속성을 구성 매개변수에 지정할 필요가 없습니다. 동시성

동시 요청 처리를 위한 도우미 메서드

axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
로그인 후 복사

인스턴스 만들기

사용자 지정 구성으로 새 axios 인스턴스를 만들 수 있습니다.

axios.all(iterable)
axios.spread(callback)
로그인 후 복사

인스턴스 메서드

사용 가능한 모든 인스턴스 메서드가 아래에 나열되어 있으며 지정된 구성이 인스턴스 구성과 병합됩니다.

axios.create([config])
varinstance=axios.create({baseURL:'https://some-domain.com/api/',timeout:1000,headers:{'X-Custom-Header':'foobar'}});
로그인 후 복사

요청 구성

사용 가능한 요청 구성 항목은 다음과 같습니다. URL만 필수입니다. 방법을 지정하지 않으면 기본 요청 방법은 GET입니다.

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
로그인 후 복사

응답 데이터 구조

응답 데이터에는 다음 정보가 포함됩니다.

{// `url` is the server URL that will be used for the requesturl:'/user',
// `method` is the request method to be used when making the requestmethod:'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:' 
// `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
// The last function in the array must return a string or an ArrayBuffertransformRequest:[function(data){
// Do whatever you want to transform the datareturndata;}],
// `transformResponse` allows changes to the response data to be made before
// it is passed to then/catchtransformResponse:[function(data){
// Do whatever you want to transform the datareturndata;}],
// `headers` are custom headers to be sentheaders:{'X-Requested-With':'XMLHttpRequest'},
// `params` are the URL parameters to be sent with the requestparams:{ID:12345},
// `paramsSerializer` is an optional function in charge of serializing `params`
// (e.g. https://www.npmjs.com/package/qs,  paramsSerializer:function(params){returnQs.stringify(params,{arrayFormat:'brackets'})},
// `data` is the data to be sent as the request body// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be a string, an ArrayBuffer or a hashdata:{firstName:'Fred'},
// `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,
// `withCredentials` indicates whether or not cross-site Access-Control requests
// should be made using credentialswithCredentials:false,
// default// `adapter` allows custom handling of requests which makes testing easier.
// Call `resolve` or `reject` and supply a valid response (see [response docs](#response-api)).adapter:function(resolve,reject,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`.auth:{username:'janedoe',password:'s00pers3cret'}
// `responseType` indicates the type of data that the server will respond with
// options are 'arraybuffer', 'blob', 'document', 'json', 'text'responseType:'json',
// default// `xsrfCookieName` is the name of the cookie to use as a value for xsrf tokenxsrfCookieName:'XSRF-TOKEN',
// default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName:'X-XSRF-TOKEN',
// default// `progress` allows handling of progress events for 'POST' and 'PUT uploads'
// as well as 'GET' downloadsprogress:function(progressEvent){
// Do whatever you want with the native progress event}}
로그인 후 복사

then 또는 catch를 사용하면 다음 응답을 받게 됩니다.

{// `data` is the response that was provided by the serverdata:{},
// `status` is the HTTP status code from the server responsestatus:200,
// `statusText` is the HTTP status message from the server responsestatusText:'OK',
// `headers` the headers that the server responded withheaders:{},
// `config` is the config that was provided to `axios` for the requestconfig:{}}
로그인 후 복사

기본 구성

각 요청 구성에 대한 기본값을 지정할 수 있습니다.

글로벌 axios 기본 구성

axios.get('/user/12345').then(function(response){console.log(response.data);console.log(response.status);console.log(response.statusText);console.log(response.headers);console.log(response.config);});
로그인 후 복사

사용자 정의 인스턴스 기본 구성

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';
로그인 후 복사

구성 우선순위

// Set config defaults when creating the instancevarinstance=axios.create({baseURL:' 
// Alter defaults after instance has been createdinstance.defaults.headers.common['Authorization']=AUTH_TOKEN;
로그인 후 복사

인터셉터

요청과 응답을 처리하기 전에 가로채거나 잡을 수 있습니다

Config will be merged with an order of precedence. The order is library defaults found inlib
/defaults.js, thendefaultsproperty of the instance, and finallyconfigargument for the request. The latter will take precedence over the former. Here's an example.
// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the libraryvarinstance=axios.create();
// Override timeout default for the library
// Now all requests will wait 2.5 seconds before timing outinstance.defaults.timeout=2500;
// Override timeout for this request as it's known to take a long timeinstance.get('/longRequest',{timeout:5000});
로그인 후 복사

인터셉터 제거:

// 添加一个请求拦截器axios.interceptors.request.use(function(config){
// Do something before request is sentreturnconfig;},function(error){
// Do something with request errorreturnPromise.reject(error);});
// 添加一个响应拦截器axios.interceptors.response.use(function(response){
// Do something with response datareturnresponse;},function(error){
// Do something with response errorreturnPromise.reject(error);});
로그인 후 복사

다음을 추가할 수 있습니다. 사용자 정의 axios 인스턴스에 대한 인터셉터:

varmyInterceptor=axios.interceptors.request.use(function(){/*...*/});axios.interceptors.request.eject(myInterceptor);
로그인 후 복사

이 기사의 사례를 읽은 후 방법을 마스터했다고 생각합니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사를 주목하세요!

관련 읽기:

VUE가 anmate.css를 사용하는 방법

css 그라데이션 색상


유용한 404 구성 요소


vue-cli 선반에 누락된 Iview 글꼴 아이콘에 대한 솔루션

위 내용은 axios가 Promise를 기반으로 HTTP 요청 클라이언트를 만드는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

http 상태 코드 520은 무엇을 의미합니까? http 상태 코드 520은 무엇을 의미합니까? Oct 13, 2023 pm 03:11 PM

HTTP 상태 코드 520은 서버가 요청을 처리하는 동안 알 수 없는 오류가 발생하여 더 구체적인 정보를 제공할 수 없음을 의미합니다. 서버가 요청을 처리하는 동안 알 수 없는 오류가 발생했음을 나타내는 데 사용됩니다. 이는 서버 구성 문제, 네트워크 문제 또는 기타 알 수 없는 이유로 인해 발생할 수 있습니다. 이는 일반적으로 서버 구성 문제, 네트워크 문제, 서버 과부하 또는 코딩 오류로 인해 발생합니다. 상태 코드 520 오류가 발생하면 웹사이트 관리자나 기술 지원팀에 문의하여 자세한 정보와 지원을 받는 것이 가장 좋습니다.

웹 페이지 리디렉션의 일반적인 애플리케이션 시나리오를 이해하고 HTTP 301 상태 코드를 이해합니다. 웹 페이지 리디렉션의 일반적인 애플리케이션 시나리오를 이해하고 HTTP 301 상태 코드를 이해합니다. Feb 18, 2024 pm 08:41 PM

HTTP 301 상태 코드의 의미 이해: 웹 페이지 리디렉션의 일반적인 응용 시나리오 인터넷의 급속한 발전으로 인해 사람들은 웹 페이지 상호 작용에 대한 요구 사항이 점점 더 높아지고 있습니다. 웹 디자인 분야에서 웹 페이지 리디렉션은 HTTP 301 상태 코드를 통해 구현되는 일반적이고 중요한 기술입니다. 이 기사에서는 HTTP 301 상태 코드의 의미와 웹 페이지 리디렉션의 일반적인 응용 프로그램 시나리오를 살펴봅니다. HTTP301 상태 코드는 영구 리디렉션(PermanentRedirect)을 나타냅니다. 서버가 클라이언트의 정보를 받을 때

약속 지키기: 약속 이행의 장점과 단점 약속 지키기: 약속 이행의 장점과 단점 Feb 18, 2024 pm 08:06 PM

일상생활에서 우리는 약속과 이행 사이에서 종종 문제에 직면합니다. 개인적인 관계에서든 비즈니스 거래에서든 약속을 이행하는 것은 신뢰 구축의 핵심입니다. 그러나 헌신의 장단점은 종종 논란의 여지가 있습니다. 이 기사에서는 약속의 장단점을 살펴보고 약속을 지키는 방법에 대한 몇 가지 조언을 제공합니다. 약속된 혜택은 분명합니다. 첫째, 헌신은 신뢰를 구축합니다. 사람이 약속을 지키면 다른 사람들이 자신을 믿을 만한 사람이라고 믿게 만듭니다. 신뢰는 사람들 사이에 확립된 유대이며, 이는 사람들을 더 나은 사람으로 만들 수 있습니다.

HTTP 200 OK: 성공적인 응답의 의미와 목적을 이해합니다. HTTP 200 OK: 성공적인 응답의 의미와 목적을 이해합니다. Dec 26, 2023 am 10:25 AM

HTTP 상태 코드 200: 성공적인 응답의 의미와 목적 탐색 HTTP 상태 코드는 서버 응답 상태를 나타내는 데 사용되는 숫자 코드입니다. 그 중 상태 코드 200은 요청이 서버에 의해 성공적으로 처리되었음을 나타냅니다. 이 기사에서는 HTTP 상태 코드 200의 구체적인 의미와 사용법을 살펴보겠습니다. 먼저 HTTP 상태 코드의 분류를 이해해 보겠습니다. 상태 코드는 1xx, 2xx, 3xx, 4xx 및 5xx의 다섯 가지 범주로 나뉩니다. 그 중 2xx는 성공적인 응답을 나타냅니다. 그리고 200은 2xx에서 가장 일반적인 상태 코드입니다.

http 요청 415 오류 해결 방법 http 요청 415 오류 해결 방법 Nov 14, 2023 am 10:49 AM

해결 방법: 1. 요청 헤더에서 Content-Type을 확인합니다. 2. 요청 본문에서 데이터 형식을 확인합니다. 3. 적절한 인코딩 형식을 사용합니다. 4. 적절한 요청 방법을 사용합니다. 5. 서버측 지원을 확인합니다.

Promise.resolve()에 대해 자세히 알아보세요. Promise.resolve()에 대해 자세히 알아보세요. Feb 18, 2024 pm 07:13 PM

Promise.resolve()에 대한 자세한 설명에는 특정 코드 예제가 필요합니다. Promise는 비동기 작업을 처리하기 위한 JavaScript의 메커니즘입니다. 실제 개발에서는 순서대로 실행해야 하는 일부 비동기 작업을 처리해야 하는 경우가 종종 있으며, 이행된 Promise 객체를 반환하기 위해 Promise.resolve() 메서드가 사용됩니다. Promise.resolve()는 Promise 클래스의 정적 메서드입니다.

HTTP 요청 시간 초과에 대해 어떤 상태 코드가 반환됩니까? HTTP 요청 시간 초과에 대해 어떤 상태 코드가 반환됩니까? Feb 18, 2024 pm 01:58 PM

HTTP 요청 시간이 초과되고 서버는 종종 504GatewayTimeout 상태 코드를 반환합니다. 이 상태 코드는 서버가 요청을 실행할 때 요청에 필요한 리소스를 얻지 못하거나 일정 시간이 지난 후에도 요청 처리를 완료하지 못함을 나타냅니다. 5xx 시리즈의 상태 코드로, 서버에 일시적인 문제나 과부하가 발생하여 클라이언트의 요청을 올바르게 처리할 수 없음을 나타냅니다. HTTP 프로토콜에서 다양한 상태 코드는 특정한 의미와 용도를 가지며, 504 상태 코드는 요청 시간 초과 문제를 나타내는 데 사용됩니다. 고객

C++를 사용하여 HTTP 스트리밍을 구현하는 방법은 무엇입니까? C++를 사용하여 HTTP 스트리밍을 구현하는 방법은 무엇입니까? May 31, 2024 am 11:06 AM

C++에서 HTTP 스트리밍을 구현하는 방법은 무엇입니까? Boost.Asio 및 asiohttps 클라이언트 라이브러리를 사용하여 SSL 스트림 소켓을 생성합니다. 서버에 연결하고 HTTP 요청을 보냅니다. HTTP 응답 헤더를 수신하고 인쇄합니다. HTTP 응답 본문을 수신하여 인쇄합니다.

See all articles