現代網絡開發在很大程度上取決於Ajax請求。儘管本機XMLHttpRequest
對象提供了此功能,但許多開發人員更喜歡使用諸如jQuery之類的庫來簡單地處理。 本文比較了兩個流行的替代方案:Superagent和Axios,通過對示例HTTP服務的請求展示了它們的功能。
密鑰差異:
XMLHttpRequest
XMLHttpRequest
庫簡介:支持同步和異步請求。 由於JavaScript是單線讀取的,因此同步請求會阻止執行,從而使異步請求成為實際選擇。 Axios和Superegent都獨家執行異步請求。 由於請求發生在後台,因此響應沒有立即可用。 收到響應後,回調功能會處理。 Axios使用承諾來管理此過程,從而提供更好的集成與其他異步代碼。超級代理的API不遵守標準的承諾模式。 在使用多個庫或自定義承諾時,Axios成為更強大的選擇。 但是,超級代理具有更廣泛的識別和一個小而有用的插件生態系統(例如,用於URL前綴)。 >
>兩個庫在基本API互動(獲取,發布,put)上都表現出色,但缺乏現代中可用的上傳進度跟踪之類的高級功能。 它們的主要好處在於他們的簡潔,可鍊式的API,用於請求配置和執行。 XMLHttpRequest
>
>安裝:
XMLHttpRequest
>
>示例API(麵包店訂單管理):
此示例使用假設的麵包店訂單管理API:
/orders?start=YYYY-MM-DD&end=YYYY-MM-DD
:在日期範圍內檢索訂單。
/orders
:創建一個新的訂單。 >
{ "chocolate": "3", "lemon": "5", "delivery": "2015-03-10", "placed": "2015-03-04" }
創建一個新訂單:>
這需要指定http方法(post),url(),請求正文(訂單詳細信息)和內容類型(/orders
)。 application/json
>
var request = require('superagent'); request.post('/orders/') .send({'chocolate': 2, 'placed': '2015-04-26'}) .type('application/json') .accept('json') .end(function(err, res) { if (err) { console.log('Error!'); } else { console.log(res.body); } });
axios.post( '/orders/', { chocolate: 2, placed: '2015-04-26' }, { headers: { 'Content-type': 'application/json', 'Accept': 'application/json' } } ) .then(function(response) { console.log(response.data); }) .catch(function(response) { console.log('Error!'); });
var xhr = new XMLHttpRequest(); xhr.open('POST', '/orders/', true); xhr.setRequestHeader('Content-type', 'application/json'); xhr.setRequestHeader('Accept', 'application/json'); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { console.log(xhr.response); } else { console.log('Error!'); } }; xhr.send(JSON.stringify({chocolate: 2, placed: '2015-04-26'}));
>
超級代理:
start
end
request.get('/orders') .query({start: '2015-04-22', end: '2015-04-29'}) .accept('json') .end(function(err, res) { // Handle error and response });
以上是瀏覽器的JavaScript HTTP庫的比較的詳細內容。更多資訊請關注PHP中文網其他相關文章!