이번에는 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 axiosPOST 요청 보내기
// 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}));
요청 방법
편의를 위해 지원되는 모든 요청 방법에 별칭을 제공합니다
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 그라데이션 색상
vue-cli 선반에 누락된 Iview 글꼴 아이콘에 대한 솔루션
위 내용은 axios가 Promise를 기반으로 HTTP 요청 클라이언트를 만드는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

이번 주에 Roundup : Firefox는 Locksmith-Like Powers를 얻는 Samsung '의 Galaxy Store가 프로그레시브 웹 앱을 지원하기 시작하고 CSS Subgrid는 Firefox에서 배송됩니다.

이번 주에 Roundup : Internet Explorer는 Edge로가는 길을 찾고 Google 검색 콘솔은 새로운 속도 보고서를 선전하고 Firefox는 Facebook의 알림을 제공합니다.

당신은 아마도 이미 CSS 변수에 익숙 할 것입니다. 그렇지 않다면 여기 2 초 개요가 있습니다. 실제로 사용자 정의 속성이라고합니다.

웹 사이트 구축은 프로그래밍입니다. HTML 및 CSS 작성은 프로그래밍입니다. 나는 프로그래머이며, 여기에 CSS- 트릭을 읽는다면, 당신은 ' re a입니다.

여기에 내가 당신이 선불 아는 것을 좋아하는 것 : 이것은 어려운 문제입니다. 당신이 여기에 착륙 한 경우, 당신은 당신이 말할 수있는 도구를 가리키기를 희망하기 때문에 여기에 착륙했다면

Picturein-Picture는 2016 년 Macos Sierra의 출시와 함께 Safari 브라우저에서 웹에서 처음으로 등장했습니다. 사용자가 팝 팝이 가능했습니다.

개츠비는 훌륭한 작업 처리 및 처리 이미지를 수행합니다. 예를 들어, 수동으로 이미지 최적화로 시간을 절약 할 수 있습니다.

나는 오늘 비율 기반 (%) 패딩에 대해 내 머리에 완전히 잘못되었다고 배웠습니다! 나는 항상 백분율 패딩이


핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

드림위버 CS6
시각적 웹 개발 도구
