axios使用初涉

看vue的時候,vue2.0推薦使用axios作http請求,今天就學一下axios基本使用。javascript

 

安裝 axiosvue

推薦npm方法(npm是node.js環境下的包管理器):java

npm install axios  

很是任性,只推薦這一種安裝方法,強迫乃們使用這種便捷的方式。以爲npm慢?或者根本無迴應?下面教你們更換電腦源npm。node

目前接觸到最多的就是淘寶npm鏡像: http://npm.taobao.org/ ios

鏡像,個人理解是複製了一份國外源地址的代碼等到本身的國內服務器,而且及時更新,這樣用戶去國內服務器訪問便可加快訪問速度。(不知道理解的對不對,歡迎指正)npm

 

安裝淘寶鏡像定製命令cnpmjson

$ npm install -g cnpm --registry=https://registry.npm.taobao.org  

$ cnpm install [模塊名稱] //安裝模塊

$ cnpm sync connect //同步模塊

//支持npm除了publish以外的全部命令

so,第一步的安裝axios你能夠換成:axios

cnpm install axios

 

axios基本用法:segmentfault

 axios get請求之參數寫在連接裏:api

axios.get('http://p.haoservice.com/Utility/GetProductList?key=8682dcb1b5c5488d84c10eb1767de0c5')
          .then(function (res) {
            console.log("請求成功:"+JSON.stringify(res))
          })
          .catch(function (error) {
            console.log("請求失敗:"+JSON.stringify(error))
          })

axios get請求之參數寫在params裏:

axios.get('http://p.haoservice.com/Utility/GetProductList',{
            params:{
                key:'8682dcb1b5c5488d84c10eb1767de0c5'
            }
        })
          .then(function (res) {
            console.log("請求成功:"+JSON.stringify(res))
          })
          .catch(function (error) {
            console.log("請求失敗:"+JSON.stringify(error))
          })

axios post請求:

axios.post('http://p.haoservice.com/Utility/GetProductList',{
            key:'8682dcb1b5c5488d84c10eb1767de0c5'
        })
          .then(function (res) {
            console.log("請求成功:"+JSON.stringify(res))
          })
          .catch(function (error) {
            console.log("請求失敗:"+JSON.stringify(error))
          })

axios 本身配置參數生成請求:

axios({
    method:'post',//方法
    url:'/user/12345',//地址
    data:{//參數
        firstName:'Fred',
        lastName:'Flintstone'
    }
});

多重併發請求(這個厲害):

function getUserAccount(){
    return axios.get('/user/12345');
}

function getUserPermissions(){
    return axios.get('/user/12345/permissions');
}

axios.all([getUerAccount(),getUserPermissions()])
    .then(axios.spread(function(acc,pers){ //spread方法至關於拆分數組 //兩個請求如今都完成
        console.log(acc)
console.log(pers) }));

 

axios提供的請求方式(對照上面的幾個實例,config配置信息:一個對象包含key:value格式的配置參數):

axios.request(config)
axios.get(url[,config])
axios.delete(url[,config])
axios.head(url[,config])
axios.options(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 配置參數列表:

{
// 請求地址
url: '/user',
// 請求類型
method: 'get',
// 請根路徑
baseURL: 'http://www.mt.com/api',
// 請求前的數據處理
transformRequest:[function(data){}],
// 請求後的數據處理
transformResponse: [function(data){}],
// 自定義的請求頭
headers:{'x-Requested-With':'XMLHttpRequest'},
// URL查詢對象
params:{ id: 12 },
// 查詢對象序列化函數
paramsSerializer: function(params){ }
// request body
data: { key: 'aa'},
// 超時設置s
timeout: 1000,
// 跨域是否帶Token
withCredentials: false,
// 自定義請求處理
adapter: function(resolve, reject, config){},
// 身份驗證信息
auth: { uname: '', pwd: '12'},
// 響應的數據格式 json / blob /document /arraybuffer / text / stream
responseType: 'json',
 
// xsrf 設置
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
 
// 下傳和下載進度回調
onUploadProgress: function(progressEvent){
Math.round( (progressEvent.loaded * 100) / progressEvent.total )
},
onDownloadProgress: function(progressEvent){},
 
// 最多轉發數,用於node.js
maxRedirects: 5,
 
// 最大響應數據大小
maxContentLength: 2000,
// 自定義錯誤狀態碼範圍
validateStatus: function(status){
return status >= 200 && status < 300;
},
// 用於node.js
httpAgent: new http.Agent({ keepAlive: treu }),
httpsAgent: new https.Agent({ keepAlive: true }),
 
// 用於設置跨域請求代理
proxy: {
host: '127.0.0.1',
port: 8080,
auth: {
username: 'aa',
password: '2123'
}
},
// 用於取消請求
cancelToken: new CancelToken(function(cancel){})
}

axios 響應數據:

{
  // 服務器迴應的數據將被包在data{}中,這點須要注意
  data: {},
 
  // `status` is the HTTP status code from the server response
  status: 200,
 
  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',
 
  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},
 
  // `config` is the config that was provided to `axios` for the request
  config: {},
 
  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}

axios請求數據格式(較爲關鍵的一點):

//axios串聯js對象爲JSON格式。爲了發送application/x-wwww-form-urlencoded格式數據

//瀏覽器中使用URLSearchParams
var params = new URLSearchParams();
params.append('param1','value1');
params.append('param2','value2');
axios.post('/foo',params);
//使用qs格式化數據
var qs = require('qs');
axios.post('/foo', qs.stringify({'bar':123}));

 

更多詳細用法,官方文檔寫的灰常灰常詳細,沒必要亂找資料。 官網傳送門: https://www.npmjs.com/package/axios

一片不錯的文檔翻譯: https://segmentfault.com/a/1190000008470355?utm_source=tuicool&utm_medium=referral

相關文章
相關標籤/搜索