搜尋
首頁web前端css教學axios如何基於Promise的HTTP請求客戶端

這次帶給大家axios如何基於Promise的HTTP請求客戶端,axios基於Promise的HTTP請求客戶端的注意事項有哪些,下面就是實戰案例,一起來看一下。

axios

基於Promise 的HTTP 要求用戶端,可同時在瀏覽器和node.js 中使用

功能特性

在瀏覽器中發送XMLHttpRequests請求

在node.js 中發送http請求

支援PromiseAPI

#攔截請求和回應

#轉換請求和回應資料

自動轉換JSON 資料

客戶端支援保護安全性免受XSRF攻擊

瀏覽器支援

安裝

使用bower:

$ bower install axios

使用npm:

$ npm install axios

範例

#發送一個GET請求

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

傳送一個POST請求

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

發送多個並發請求

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

可以透過給axios傳遞對應的參數來自訂請求:

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

#請求方法別名

為方便起見,我們為所有支援的請求方法都提供了別名

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 、method和data屬性不需要在config 參數裡面指定。

並發

處理並發請求的幫助方法

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

建立一個實例

你可以用自訂組態建立一個新的 axios 實例。

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

實例方法

所有可用的實例方法都列在下面了,指定的配置將會和該實例的配置合併。

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是必要的。如果沒有指定method,預設的請求方法是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}}

回應的資料結構

回應的資料包括下面的資訊:

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

當使用then或catch時, 你會收到下面的回應:

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 預設設定

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

攔截器

你可以在處理then或catch之前攔截請求和回應

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

移除一個攔截器:

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

你可以給一個自訂的axios 實例新增攔截器:

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

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

相關閱讀:

VUE如何使用anmate.css

css的漸層顏色

好用的404元件

解決Iview在vue-cli架上字體圖示遺失的方法

以上是axios如何基於Promise的HTTP請求客戶端的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
每周平台新聞:Galaxy Store的Web應用程序,Tappable Stories,CSS Subgrid每周平台新聞:Galaxy Store的Web應用程序,Tappable Stories,CSS SubgridApr 14, 2025 am 11:20 AM

在本週的綜述中:Firefox獲得了類似鎖匠的力量,三星的Galaxy Store開始支持Progressive Web Apps,CSS Subgrid正在Firefox發貨

每周平台新聞:Internet Explorer模式,搜索控制台中的速度報告,限制通知提示每周平台新聞:Internet Explorer模式,搜索控制台中的速度報告,限制通知提示Apr 14, 2025 am 11:15 AM

在本週的綜述中:Internet Explorer進入Edge,Google搜索控制台吹捧新的速度報告,而Firefox給出了Facebook' s Notification

CSS自定義屬性的範圍的功率(和樂趣)CSS自定義屬性的範圍的功率(和樂趣)Apr 14, 2025 am 11:11 AM

您可能至少已經對CSS變量有點熟悉了。如果沒有,這是兩秒鐘的概述:它們真的稱為自定義屬性

我們是程序員我們是程序員Apr 14, 2025 am 11:04 AM

構建網站正在編程。編寫HTML和CSS正在編程。我是程序員,如果您在這裡閱讀CSS-Tricks,那麼您很有可能是您

您如何從網站上刪除未使用的CSS?您如何從網站上刪除未使用的CSS?Apr 14, 2025 am 10:59 AM

在這裡,我想預先知道的是:這是一個很難的問題。如果您降落在這裡,因為您希望指向您可以運行的工具

圖片中的圖片網絡API簡介圖片中的圖片網絡API簡介Apr 14, 2025 am 10:57 AM

圖片中的圖片在2016年發行了Macos Sierra,在Safari瀏覽器中首次出現在網絡上。這使用戶可以彈出

使用Gatsby組織和準備圖像以使圖像模糊效果的方法使用Gatsby組織和準備圖像以使圖像模糊效果的方法Apr 14, 2025 am 10:56 AM

蓋茨比(Gatsby)進行了出色的處理和處理圖像。例如,它可以幫助您節省圖像優化的時間,因為您不必手動

哦,嘿,填充百分比基於父元素的寬度哦,嘿,填充百分比基於父元素的寬度Apr 14, 2025 am 10:55 AM

今天,我學到了一些有關基於百分比的(%)填充的知識,我腦海中完全錯了!我一直認為百分比填充是基於

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。