Axios是一個基於promise的HTTP庫,能夠用在瀏覽器和node.js中javascript
$ npm install axios
$ bower install axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
//4.響應的json數據自動解析爲js的對象/數組 function axios({ url, method='GET', params={}, data={} }) { //返回一個Promise對象 return new Promise((resolve,reject) => { //處理method(轉大寫) method = method.toUpperCase() //處理query參數(拼接到url上) id=1&xxx=abc /* { id: 1, xxx: 'abc' } */ let queryString = '' Object.keys(params).forEach(key => { queryString += `${key}=${params[key]}&` }) if (queryString) { // 去除最後的& queryString = queryString.substring(0,queryString.length-1) // 接到url url += '?' + queryString } //1.執行異步ajax請求 //建立xhr對象 const request = new XMLHttpRequest() //打開鏈接(初始化請求,沒有請求) request.open(method, url, true) //發送請求 if (method === 'GET' || method === 'DELETE') { request.send() //異步的 }else if(method==='POST' || method === 'PUT'){ request.setRequestHeader('Content-Type','application/json;charset=utf-8')//告訴服務器請求體的格式是 request.send(JSON.stringify(data)) //發送json格式的請求參數 } //綁定狀態的監聽 request.onreadystatechange = function () { //發送請求是異步的,綁定狀態的監聽爲同步所以該函數放哪前面和後面均可以 if (request.readyState !== 4) { return } // 若是響應狀態碼在[200,300]之間表明成功,不然失敗 //es6解構賦值 const {status, statusText} = request //若是請求成功了,調用resolve() if (status>=200 && status<=299) { // 準備結果數據對象response const response = { data:JSON.parse(request.response), //響應體解析好的數據 status, //響應體的狀態碼 statusText //響應體對應的文本 } resolve(response) }else{ //若是請求失敗了,調用reject() reject(new Error('request error status is ' + status)) } } }) }
在文檔中具備三個經常使用的全局axios默認值:java
axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; //傳入token axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';在發送前編碼全部字符,此設置是默認設置。
咱們經常使用的設置是axios.defaults.baseURL,用於定義url地址,使得咱們在參數傳遞時,只傳遞參數對應參數便可。例:node
// 指定默認配置 axios.defaults.baseURL = 'http://localhost:3000' /* 1.GET請求:從服務器端獲取數據 */ function testGet(){ axios({ url:'/posts', params:{ id:1 } }).then(response => { console.log('/posts get',response.data) }) } /* 2.POST請求:向服務端去存儲數據 */ function testPost() { axios({ url:'/posts', method:'post', data:{title: "json-server4", author: "typicode4"} }).then(response => { console.log('/posts post',response.data) }) } /* 3.PUT請求:更新服務器已經數據 */ function testPut() { axios({ url:'/posts/4', method:'put', data:{title: "json-server5", author: "typicode5"} }).then(response => { console.log('/posts put',response.data) }) } /* 4.DELETE請求:刪除服務器端的數據 */ function testDelete() { axios({ url:'/posts/4', method:'delete', }) .then(response => { console.log('/posts delete',response.data) }) }
咱們爲何要設計自定義實例?ios
const instance = axios.create({ baseURL : 'http://localhost:4000' }) //使用instance發請求 instance({ url:'/xxx' //請求4000 }) instance.get('/xxx') //建立第二個實例,用於更改不一樣的配置 const instance2 = axios.create({ baseURL:'htto://localhost:8081' }) instance2({ url:'/yyy' }) instance2.get('/yyy')
//添加請求攔截器(回調函數) axios.interceptors.request.use( config => { //在發送請求請求以前會執行下列以下 console.log('request interceptor1 onResolved()') return config }, error =>{ //在發送請求失敗會執行下列以下 console.log('request interceptor1 onRejected()') return Promise.reject(error) } ) //添加響應函數 axios.interceptors.response.use( response => { //在響應數據成功後會執行以下 console.log('response interceptor1 onResolved') return response }, function(error){ //在響應數據失敗後會執行以下 console.log('response interceptor1 onRejected') return Promise.reject(error) } ) // 發送請求 axios.get('http://localhost:3000/posts') .then(response => { console.log('data',response.data) }) .catch(error => { console.log('error',error.message) })
當咱們點擊按鈕進行發送請求的時候,若是此時請求正在發送中,而用戶殊不知曉,用戶可能會重複點擊按鈕進行發送請求,此時咱們使用撤銷請求,若是當前請求還正在響應,用戶再次點擊按鈕則會取消上次正在發送的請求,防止服務器接收多個請求,並屢次作出響應。
實例:es6
//定義攔截器模塊 //添加請求攔截器 axios.interceptors.request.use((config) => { //在準備發請求前,取消未完成的請求,使得重複點擊時,取消上次發送的請求 if (typeof cancel === 'function') { cancel('取消請求') } //給config添加一個cancelToken的配置 config.cancelToken = new CancelToken(function executor(c) { //c 是用於取消當前請求的函數 // 保存取消函數,用於以後可能須要取消當前的請求 cancel = c; }) return config }) //添加響應攔截器 axios.interceptors.response.use( //當響應成功後,取消在發送請求時添加的撤銷函數 response => { cancel = null return response }, error => { if (axios.isCancel(error)) { console.log('請求取消的錯誤',error.message) //中斷Promise鏈 上面要中斷請求 return new Promise(() => {}) }else{ //請求出錯了 cancel = null // console.log('請求1失敗了',error.message) //將錯誤向下傳遞 // throw error 下面要將錯誤向下傳遞 return Promise.reject(error) } } ) //引入CancelToken 構造函數 const CancelToken = axios.CancelToken; let cancel //用於保存請求的函數 function getProduct1() { axios({ url:'http://localhost:4000/products1', }).then( response => { console.log('請求1成功了',response.data) }, error => {//只用於處理請求失敗的狀況,取消請求的錯誤不用 console.log('請求1失敗了',error.message) } ) }
/* 撤銷請求 */ function cancelReq() { // alert('取消請求') //執行取消請求的函數 //沒有點過發送數據的按鈕,當點擊過發送數據的按鈕後cancel將會存儲一個函數 //故須要在強制取消請求時判斷cancel是不是一個函數,若是是函數說明還正在發送請求中 if (typeof cancel === 'function' ) { cancel('強制取消請求') } else{ console.log('沒有可取消的請求') } }
以上爲axios的總結啦,有幫助的話就點個讚唄!ajax
具體應用也能夠到官方文檔進行查看官方中文文檔npm