當前位置:首頁 » 數據倉庫 » 前端如何配置全局axios
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

前端如何配置全局axios

發布時間: 2022-12-23 15:00:27

A. vue的http請求主要是用什麼插件

axios

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

功能特性

在瀏覽器中發送XMLHttpRequests請求

在 node.js 中發送http請求

支持PromiseAPI

攔截請求和響應

轉換請求和響應數據

自動轉換 JSON 數據

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


安裝

使用 bower:

$ bower install axios

使用 npm:

$ npm install axios

例子

發送一個GET請求

//
axios.get('/user?ID=12345')
.then(function(response){
console.log(response);
})
.catch(function(response){
console.log(response);
});
//
axios.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){
//Bothrequestsarenowcomplete
}));

axios API

可以通過給axios傳遞對應的參數來定製請求:

axios(config)
//SendaPOSTrequestaxios({method:'post',url:'/user/12345',
data:{firstName:'Fred',lastName:'Flintstone'}});
axios(url[,config])
//SnedaGETrequest(defaultmethod)
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`
url:'/user',
//`method`
method:'get',//default
//`baseURL`willbeprependedto`url`unless`url`isabsolute.
//Itcanbeconvenienttoset`baseURL`
//tomethodsofthatinstance.
baseURL:'https://some-domain.com/api/',
//`transformRequest`
//'PUT','POST',and'PATCH'
//
transformRequest:[function(data){
//
returndata;
}],
//`transformResponse`
//itispassedtothen/catch
transformResponse:[function(data){
//
returndata;
}],
//`headers`arecustomheaderstobesent
headers:{'X-Requested-With':'XMLHttpRequest'},
//`params`
params:{
ID:12345
},
//`paramsSerializer``params`
//(e.g.https://www.npmjs.com/package/qs,http://api.jquery.com/jquery.param/)
paramsSerializer:function(params){
returnQs.stringify(params,{arrayFormat:'brackets'})
},
//`data`
//'PUT','POST',and'PATCH'
//Whenno`transformRequest`isset,mustbeastring,anArrayBufferorahash
data:{
firstName:'Fred'
},
//`timeout`.
//Iftherequesttakeslongerthan`timeout`,therequestwillbeaborted.
timeout:1000,
//`withCredentials`indicateswhetherornotcross-siteAccess-Controlrequests
//shouldbemadeusingcredentials
withCredentials:false,//default
//`adapter`.
//Call`resolve`or`reject`andsupplyavalidresponse(see[responsedocs](#response-api)).
adapter:function(resolve,reject,config){
/*...*/
},
//`auth`,andsuppliescredentials.
//Thiswillsetan`Authorization`header,overwritinganyexisting
//`Authorization`customheadersyouhavesetusing`headers`.
auth:{
username:'janedoe',
password:'s00pers3cret'
}
//`responseType`
//optionsare'arraybuffer','blob','document','json','text'
responseType:'json',//default
//`xsrfCookieName`
xsrfCookieName:'XSRF-TOKEN',//default
//`xsrfHeaderName`
xsrfHeaderName:'X-XSRF-TOKEN',//default
//`progress`'POST'and'PUTuploads'
//aswellas'GET'downloads
progress:function(progressEvent){
//
}
}

響應的數據結構

響應的數據包括下面的信息:

{
//`data`
data:{},
//`status`
status:200,
//`statusText`
statusText:'OK',
//`headers`
headers:{},
//`config`istheconfigthatwasprovidedto`axios`fortherequest
config:{}
}

當使用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';

自定義實例默認配置

//
varinstance=axios.create({
baseURL:'https://api.example.com'
});
//
instance.defaults.headers.common['Authorization']=AUTH_TOKEN;

配置的優先順序

./defaults.js,,..Here'sanexample.
//
//`0`=axios.create();
//
//Nowallrequestswillwait2..defaults.timeout=2500;
//'sknowntotakealongtimeinstance.get('
/longRequest',{timeout:5000});

攔截器

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

// 添加一個請求攔截器

axios.interceptors.request.use(function(config){
//
returnconfig;
},function(error){
//Dosomethingwithrequesterror
returnPromise.reject(error);
});



// 添加一個響應攔截器

axios.interceptors.response.use(function(response){
//Dosomethingwithresponsedata
returnresponse;
},function(error){
//Dosomethingwithresponseerror
returnPromise.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){
//
console.log('Error',response.message);
}else{
//Therequestwasmade,
//thatfallsoutoftherangeof2xx
console.log(response.data);
console.log(response.status);
console.log(response.headers);
console.log(response.config);
}
});

Promises

axios 依賴一個原生的 ES6 Promise 實現,如果你的瀏覽器環境不支持 ES6 Promises,你需要引入polyfill

B. axios中的請求攔截器怎麼用

vue-resource不再維護之後,我也用起了axios,但是死活無法設置伺服器發送過來的cookie

後來查詢文檔發現,這個是要單獨配置的。
// `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default
當我們把此配置項設置成默認配置項並且設置成true的時候,axios就可以設置cookies了。
全局默認配置設置方法:
axios.defaults.withCredentials=true
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

C. 前端環境的安裝與配置

前端環境的安裝與配置?一、工具安裝
1.編輯器
2.Git(分布式的代碼管理工具)
3.Photoshop
4.Nodejs鏈接
二、 環境配置
1.配置git:

1.1 設置Git的user name和email:
$ git config --global user.name "name"
$ git config --global user.email "[email protected]"
1.2 生成SSH密鑰過程:(看需求配置)
$ ssh-keygen -t rsa -C "[email protected]"

3個回車,密碼為空。
Your identification has been saved in /home/tekkub/.ssh/id_rsa.
Your public key has been saved in /home/tekkub/.ssh/id_rsa.pub.
The key fingerprint is:

………………

最後得到了兩個文件:id_rsa和id_rsa.pub

添加密鑰到ssh:

登陸gitlab, Profile Settings -> SSH Keys -> ADD SSH KEYS ,找到本地的id_rsa.pub文件,復制出裡面的內容,添加到 key 內,此時 Title 會自動填上你的郵箱,沒有的話手動填寫, ADD KEY
1.3 拉取代碼到本地(許可權)

創建一個存放項目的文件夾,在該文件夾下,單擊右鍵,選擇git bash,打開git命令框,編寫命令:git clone [email protected]:xx/xx.git(可以在gitlab項目中找到存放地址,gitlab地址:http://gitlab.vchangyi.com ),按回車,就可以從gitlab上clone代碼到本地文件夾
1.4 手動安裝nodejs,如果是pc端安裝的話,nodejs版本不能過低。

安裝最新版的話npm安裝項目依賴會有問題,手機端gulp無法啟動,所以建議安裝nodejs V6。
1.5 測試node是否安裝成功

在git 命令窗或者node 命令窗中輸入命令 :node -v
1.6 同理,測試npm是否安裝成功npm -v
1.7安裝gulp

在項目下打開git 命令窗,從淘寶源上自行安裝,這個時間需要等待和耐心,也會有網路原因導致安裝失敗,如果安裝失敗可以多來幾次,直到成功為止。
如果是pc端:npm install --registry=http://registry.npm.taobao.org --phantomjs_cdnurl=http://cnpmjs.org/downloads

npm 安裝時候 持久使用淘寶源 設置:
npm config set registry https://registry.npm.taobao.org
配置後可通過下面方式來驗證是否成功
npm config get registry


npm info express