Heim  >  Artikel  >  Web-Frontend  >  Wie Axios den Promise-basierten HTTP-Anfrage-Client verwendet

Wie Axios den Promise-basierten HTTP-Anfrage-Client verwendet

php中世界最好的语言
php中世界最好的语言Original
2018-03-09 17:09:202275Durchsuche

Dieses Mal zeige ich Ihnen, wie Axios einen Promise-basierten HTTP-Anfrage-Client verwendet. Was sind die Vorsichtsmaßnahmen für den Promise-basierten HTTP-Anfrage-Client?

axios

Promise-basierter HTTP-Request-Client, der gleichzeitig in Browsern und node.js verwendet werden kann

Funktionsmerkmale

XMLHttpRequests im Browser senden

HTTP-Anfragen in node.js senden

Support PromiseAPI

Anfragen und Antworten abfangen

Anfragen und Antworten konvertieren Daten

JSON-Daten automatisch konvertieren

Client-Unterstützung zum Schutz der Sicherheit vor XSRF-Angriffen

Browser-Unterstützung

Installation

Bower verwenden:

$ bower install axios

Verwenden Sie npm:

$ npm install axios

Beispiel

Senden Sie eine GET-Anfrage

// 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);});

Senden Sie einePOST-Anfrage

axios.post('/user',{firstName:'Fred',lastName:'Flintstone'}).then(function(response){console.log(response);}).catch(function(response){console.log(response);});

Mehrere gleichzeitige Anfragen senden

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-API

kann durch Übergabe entsprechender Parameter an Axios-Anfragen angepasst werden:

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');

Anfragemethoden Aliase

Der Einfachheit halber haben wir Aliase

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]])

für alle unterstützten Anfragemethoden bereitgestellt. Hinweis

Wann Bei Verwendung der Alias-Methode müssen die URL-, Methoden- und Datenattribute nicht in den Konfigurationsparametern angegeben werden.

Parallelität

Hilfsmethoden für die Verarbeitung gleichzeitiger Anfragen

axios.all(iterable)
axios.spread(callback)

Eine Instanz erstellen

Sie können eine neue Axios-Instanz mit benutzerdefinierter Konfiguration erstellen.

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

Instanzmethoden

Alle verfügbaren Instanzmethoden sind unten aufgeführt und die angegebene Konfiguration wird mit der Konfiguration der Instanz zusammengeführt.

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]])

Anforderungskonfiguration

Im Folgenden sind die verfügbaren Anforderungskonfigurationselemente aufgeführt, nur die URL ist erforderlich. Wenn keine Methode angegeben ist, ist die Standardanforderungsmethode GET.

{// `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}}

Antwortdatenstruktur

Die Antwortdaten enthalten die folgenden Informationen:

{// `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:{}}

Bei Verwendung von then oder Catch erhalten Sie die folgende Antwort:

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);});

Standardkonfiguration

Sie können die Standardkonfiguration für jede Anfrage angeben.

Globale Axios-Standardkonfiguration

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';

Benutzerdefinierte Instanz-Standardkonfiguration

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

Priorität der Konfiguration

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});

Interceptor

Sie können Anfragen und Antworten abfangen, bevor Sie sie bearbeiten, oder sie abfangen.

// 添加一个请求拦截器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);});

Entfernen Sie einen Interceptor:

varmyInterceptor=axios.interceptors.request.use(function(){/*...*/});axios.interceptors.request.eject(myInterceptor);

Sie können einen Interceptor zu einer benutzerdefinierten Axios-Instanz hinzufügen:

varinstance=axios.create();instance.interceptors.request.use(function(){/*...*/});
错误处理
axios.get('/user/12345').catch(function(response){if(responseinstanceofError){
// Something happened in setting up the request that triggered an Errorconsole.log('Error',response.message);}else{
// The request was made, but the server responded with a status code
// that falls out of the range of 2xxconsole.log(response.data);console.log(response.status);console.log(response.headers);console.log(response.config);}});
Promises
axios 依赖一个原生的 ES6 Promise 实现,如果你的浏览器环境不支持 ES6 Promises,你需要引入polyfill
TypeScript
axios 包含一个TypeScript定义
/// import*asaxiosfrom'axios';axios.get('/user?ID=12345');
Credits
axios is heavily inspired by the$http serviceprovided inAngular. Ultimately axios is an effort to provide a standalone$http-like service for use outside of Angular.
License
MIT

Ich glaube, dass Sie die Methode beherrschen, nachdem Sie den Fall in diesem Artikel gelesen haben. Weitere spannende Informationen finden Sie in anderen verwandten Artikeln auf der chinesischen PHP-Website!

Verwandte Lektüre:

Wie VUE anmate.css verwendet

Verlaufsfarbe von CSS

Nützliche 404-Komponenten

So lösen Sie das Problem, dass das Iview-Schriftartsymbol im Vue-CLI-Regal fehlt

Das obige ist der detaillierte Inhalt vonWie Axios den Promise-basierten HTTP-Anfrage-Client verwendet. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:Wie VUE anmate.css verwendetNächster Artikel:Wie VUE anmate.css verwendet