国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

JavaScript中怎么發(fā)出HTTP請求

發(fā)布時(shí)間:2021-07-04 20:13 來(lái)源:億速云 閱讀:0 作者:Leah 欄目: 開(kāi)發(fā)技術(shù)

這篇文章給大家介紹JavaScript中怎么發(fā)出HTTP請求,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

XMLHttpRequest

XMLHttpRequest對象可用于從Web請求數據。它是這次比較中最早的方法,盡管其他選擇都優(yōu)于它,但由于其向后兼容性和成熟度,它仍然有效且有用。

得到:

var req= new XMLHttpRequest();//The onreadystatechange property //specifies a function to be //executed every time the status //of the XMLHttpRequest changes req.onreadystatechange = function() {     if (this.readyState == 4 &&this.status == 200) {        //The responseText property        //returns a text string                  console.log(xhttp.responseText)        //Do some stuff     } };req.open("GET", "http://dataserver/users", true); req.send();

發(fā)送:

varformData = new FormData(); formData.append("name", "Murdock"); var req = new XMLHttpRequest(); req.open("POST", "http://dataserver/update"); req.send(formData);

優(yōu)點(diǎn):

  • 不需要從外部源加載

  • 向后兼容性

  • 成熟/穩定

  • 在所有瀏覽器中均可使用

  • 是原生瀏覽器API

缺點(diǎn):

  • 支持回調地獄

  • 笨拙冗長(cháng)的語(yǔ)法

  • Fetch能自然地替代它

Qwest

Qwest是一個(gè)基于Promise的簡(jiǎn)單ajax庫,它支持XmlHttpRequest2的獨立數據,例如ArrayBuffer,Blob和FormData。

得到:

qwest.get('http://dataserver/data.json')      .then(function(xhr, response) {         // ...do some stuff whith data      });

發(fā)送:

qwest.post('http://dataserver/update',{         firstname: 'Murdock',               age: 30      })      .then(function(xhr, response) {         // Make some useful actions      })      .catch(function(e, xhr, response) {         // Process the error      });

優(yōu)點(diǎn):

  • 可以建立請求限制

  • 基于Promise

缺點(diǎn):

  • 并非所有瀏覽器上都可使用XmlHttpRequest2

  • 非原生

  • 必須從外部源加載

JQuery.ajax

該庫在不久前被廣泛用于發(fā)出HTTP異步請求。jQuery的所有Ajax方法都返回XMLHTTPRequest對象的超集

得到:

$.ajax({     url: 'http://dataserver/data.json'   }).done(function(data) {     // ...do some stuff whith data   }).fail(function() {     // Handle error });

發(fā)送:

$.ajax({   type: "POST",   url: 'http://dataserver/update',   data: data,   success: successCallBack,   error: errorCallBack,   dataType: dataType });

優(yōu)點(diǎn):

  • 良好的支持和文檔

  • 可配置的對象

  • 在許多項目中使用

  • 學(xué)習曲線(xiàn)低

  • 它返回XMLHttpRequest對象,因此可以中止請求

缺點(diǎn):

  • 非原生

  • 必須從外部源加載

  • 沒(méi)有與Promises結合

  • 對于原生ES6 Fetch不是必需的。

Axios

圖源:unsplash

基于Promise的HTTP庫,用于在瀏覽器和Nodejs上執行HTTP請求。

得到:

axios({   url: 'http://dataserver/data.json',   method: 'get' })

發(fā)送:

axios.post('http://dataserver/update',{     name: 'Murdock'   })   .then(function (response) {     console.log(response);   })   .catch(function (error) {     console.log(error);   });

優(yōu)點(diǎn):

  • 使用promise避免回調地獄

  • 在瀏覽器和Nodejs上均可使用

  • 支持上傳進(jìn)度

  • 可以設置響應超時(shí)

  • 通過(guò)簡(jiǎn)單地向其傳遞配置對象即可配置請求

  • Axios已實(shí)現可撤銷(xiāo)的promise提議

  • 自動(dòng)將數據轉換為JSON

缺點(diǎn):

  • 非原生

  • 必須從外部源加載

SuperAgent

SuperAgent是ajax API,旨在提供靈活性,可讀性和較低的學(xué)習曲線(xiàn)。它也可以與Node.js一起使用。

得到:

request('GET','http://dataserver/data.json').then( success, failure);

.query()方法接受對象,這些對象與GET方法一起使用時(shí)將形成查詢(xún)字符串。以下代碼將產(chǎn)生路徑/ dataserver / search?name =  Manny&lastName = Peck&order = desc。

request    .get('/dataserver/search')    .query({ name: 'Templeton' })    .query({ lastname: 'Peck' })    .query({ order: 'desc' })    .then(res => {console.dir(res)} });

發(fā)送:

request    .post('http://dataserver/update')    .send({ name: 'Murdock' })    .set('Accept', 'application/json')    .then(res => {       console.log('result' +JSON.stringify(res.body));    });

優(yōu)點(diǎn):

  • 基于Promise

  • 在Node.js和瀏覽器中均可使用

  • 可以調用request.abort()方法中止請求

  • 社區的知名庫

  • 發(fā)出HTTP請求的無(wú)縫接口

  • 出現故障時(shí)支持重試請求

缺點(diǎn):

  • 它不支持以XMLHttpRequest的形式監視加載進(jìn)度

  • 非原生

  • 必須從外部源加載

圖源:unsplash

Http-client

Http-client允許使用JavaScript的訪(fǎng)存API組成HTTP客戶(hù)端。

得到:

//usingES6 modules import { createFetch, base, accept, parse } from 'http-client'const fetch =createFetch(  base('http://dataserver/data.json'),    accept('application/json'),       parse('json')                      )fetch('http://dataserver/data.json').then(response => {   console.log(response.jsonData) })

發(fā)送:

//usingES6 modules import { createFetch, method, params } from 'http-client'const fetch =createFetch(   params({ name: 'Murdock' }),   base('http://dataserver/update') )

優(yōu)點(diǎn):

  • 在Node.js和瀏覽器中均可使用

  • 服務(wù)器端工作人員使用

  • 基于Promise

  • 提供頭部保護裝置,以提高CORS的安全

缺點(diǎn):

  • 必須從外部源加載

  • 非原生

Fetch

Fetch是原生瀏覽器API,用于發(fā)出替代XMLHttpRequest的請求。與XMLHttpRequest相比,Fetch使網(wǎng)絡(luò )請求更容易。Fetch  API使用Promises避免XMLHttpRequest回調地獄。

得到:

//WithES6 fetch fetch('http://dataserver/data.json')   .then(data => {     // ...do some stuff whith data   }).catch(error => {     // Handle error });

發(fā)送:

fetch('http://dataserver/update',{   method: 'post',   headers: {     'Accept': 'application/json,text/plain, */*',     'Content-Type': 'application/json'   },   body: JSON.stringify({name: 'Murdock'}) }).then(res=>res.json())   .then(res => console.log(res));//ORwith ES2017 for example(async () => {     const response = awaitfetch('http://dataserver/update', {     method: 'POST',     headers: {       'Accept': 'application/json',       'Content-Type': 'application/json'     },     body:JSON.stringify({name='Murdock'})   });const result = awaitresponse.json();console.log(result); })();

優(yōu)點(diǎn):

  • 是原生瀏覽器API

  • Fetch基本上是經(jīng)過(guò)完善的XMLHttpRequest

  • 友好且易于學(xué)習

  • 與大多數最近使用的瀏覽器兼容

  • 是原生XMLHttpRequest對象的自然替代

  • 學(xué)習曲線(xiàn)低

  • 不需要從外部源加載它

  • 使用promises避免回調地獄

  • 不需要更多依賴(lài)項

缺點(diǎn):

  • 處理JSON數據的過(guò)程分為兩步。第一個(gè)是發(fā)出請求,然后第二個(gè)是在響應時(shí)調用.json()方法。對于A(yíng)xios,默認情況下會(huì )收到JSON響應。

  • 從Fetch()返回的Promise僅在網(wǎng)絡(luò )故障或任何阻止請求完成的情況發(fā)生時(shí)拒絕。即使響應為HTTP  404或500,也不會(huì )拒絕HTTP錯誤狀態(tài)。

  • 缺乏其他庫的一些有用功能,例如:取消請求。

  • 默認情況下,Fetch不會(huì )從服務(wù)器發(fā)送或接收Cookie,如果站點(diǎn)依賴(lài)于維持用戶(hù)會(huì )話(huà),則會(huì )導致未經(jīng)身份驗證的請求。但是可以通過(guò)添加以下內容來(lái)啟用:

  • {credentials: “same-origin.”}

Fetch是一個(gè)新標準,新版本的Chrome和Firefox無(wú)需使用任何其他庫就可支持它。

此外,Axios,SuperAgent或其他庫都有適合的文檔,易于使用,并且學(xué)習曲線(xiàn)不太高。在某些情況下,它們可以提供Fetch不具有的功能。

Fetch在JavaScript里是原生的,足以滿(mǎn)足項目需求。如果沒(méi)有特殊需求,我認為Fetch就是最合適的選擇。

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。

18禁黄网站禁片免费观看APP| 中文字幕无线码中文字幕免费| 亚洲AV无码专区在线电影成人| 久久97精品久久久久久久不卡| 在线观看人成视频免费不卡| 成人综合激情另类小说|