最近學習態度比較積極,打算用react作一個小我的應用網站...因此從阿里雲上買了些免費的接口,什麼QQ音樂排行查詢接口、IP地址查詢、天氣預報等等。調用時,發現身份校驗能夠經過簡單修改頭部信息的方式,即向頭部加入APPCODE的key,以及相應的值。react
可是以前沒有用過請求頭添加 so 記錄學習下...ajax
1、首先直接放demojson
一、jQueryapi
var requestUrl = "http://ali-qqmusic.showapi.com/top?topid=6"; $.ajax({ type : "get", url : requestUrl , dataType : "json" , success: function(data) { console.log(data); }.bind(this), beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "APPCODE ....................."); } });
使用ajax的beforeSend方法向頭部添加信息跨域
二、fetch瀏覽器
let requestUrl = "http://ali-qqmusic.showapi.com/top?topid=6"; fetch(requestUrl, { method: "get", headers: { Authorization: "APPCODE ......................" } }).then(response => response.json()).then(data => console.log(data)).catch(e => console.log(e));
哈哈哈哈,其實有點寵fetch,這個時用ES6來寫。接下來來整理下相關API,以及簡單介紹下fetch服務器
2、記錄jQuery ajax 時不時使用,可是快遺忘的API方法cookie
ajax 經常使用的方法,什麼url、type、dataType、success之類的就不提了網絡
一、async 默認是true表示請求爲異步請求,若是設置爲false表示同步,ajax下面的方法要等請求結束後纔會調用app
二、beforeSend(xhr) 用於發送請求前修改XMLHttpRequest對象的函數,主要用做修改http頭部,就像上面的demo
三、context 用於綁定回調函數的上下文,即this,設置了它就至關於在回調函數上加入了bind(context)同樣
四、jsonp 用於跨域操做,重寫回調函數的名字
五、timeout 請求超時時間
六、complete(xhr , ts) 不管請求成功or失敗的回調函數
3、fetch
以前一直沒用用過這種請求方式,如今看來這種請求方式代碼顯得十分的優美,畢竟Fetch API是基於Promises設計的。fetch是瀏覽器提供的原生網絡請求接口,可是它的兼容性仍是有所欠缺的,具體兼容狀況以下圖
經常使用的寫法有兩種
//方式一 fetch('./api/XXX.json') .then( function(response) { if(response.status !== 200) { console.log('Status Code: ' + response.status); return; } response.json().then(function(data) { console.log(data); }); } ) .catch(function(err) { console.log(err); }); //方式二 function status(response) { if (response.status == 200) { return Promise.resolve(response) } else { return Promise.reject(new Error(response.statusText)) } } function json(response) { return response.json() } fetch('./api/XXX.json').then(status).then(json) .then(function(data) { console.log(data); }).catch(function(err) { console.log('err); });
在fetch方法中,首先返回的response對象,so 第一個then中的函數參數爲res,而後經過響應的狀態碼判斷請求是否成功,成功後調用response的json()方法,這個也是返回一個Promise對象,因此能夠連續then,最後的catch能夠抓取代碼執行時的異常信息。
而後就是fetch第一個參數爲URL,第二個參數能夠加入請求方式、頭信息、表單信息等
fetch(url, { method: 'post', headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, body: 'foo=bar&lorem=ipsum' })
最後就是fetch中的一些坑,沒遇到過,先記錄下。
一、Fetch 請求默認是不帶 cookie 的,須要設置 fetch(url, {credentials: 'include'})
二、服務器返回 400,500 錯誤碼時並不會 reject,只有網絡錯誤這些致使請求不能完成時,fetch 纔會被 reject。
搞定!!!