vue reqwest與fetch的使用

2022-02-28 09:47:30 字數 1390 閱讀 9092

**:

很多人看到reqwest,第一感覺就是:「哎,哥們你寫錯了吧,應該是request吧。」 額,表示很傷〜真的沒寫錯.

reqwest的使用,官方npm包說的很直白。

it's ajax

all over again. includes support for xmlhttprequest, jsonp, cors, and commonjs promises a.

普通的reqwest寫法跟ajax大抵差不多,像下面這樣:

// 普通請求

reqwest(  // 入參

, error: function (err)

, success: function (resp)

})// jsonp請求

reqwest(

, success: function (resp)

})// cors請求

reqwest(

, success: function (resp)

})// promise寫法

reqwest()

.then(function (resp) , function (err, msg) )

.always(function (resp) )

// 請求html 

fetch('/users.html')

.then(function(response) ).then(function(body) )

// 提交json資料

fetch('/users', ,

body: json.stringify()

})// cors請求

fetch('', )

fetch的mode配置項有3個值,如下:

same-origin:該模式是不允許跨域的,它需要遵守同源策略,否則瀏覽器會返回乙個error告知不能跨域;

其對應的response type為basic。

cors: 該模式支援跨域請求,顧名思義它是以cors的形式跨域;當然該模式也可以同域請求不需要後端額外的cors支援;

其對應的response type為cors。

no-cors: 該模式用於跨域請求但是伺服器不帶cors響應頭,也就是服務端不支援cors;這也是fetch的特殊跨域請求方式;

其對應的response type為opaque

// fetch不支援jsonp,那麼需要叫上他的兄弟fetchjsonp

fetchjsonp('/users.jsonp')

.then(function(response) ).then(function(json) ).catch(function(ex) )

React Native 之 網路請求 fetch

前言 fetch url,init then response then responsedata catch error done 譯註 下面是乙個最基本的請求,只傳入乙個引數,預設為get方式請求 fetch url then response response.json json方式解析,如果...

React Native專案實戰之fetch請求

摘要 fetch簡介 在 ajax 時代,進行請求 api 等網路請求都是通過xmlhttprequest 或者封裝後的框架進行網路請求。而在前端快速發展地過程中,為了契合更好的設計模式,產生了 fetch 框架。在 chrome 瀏覽器中已經全域性支援了 fetch 函式,開啟除錯工具,在 con...

React Native專案實戰之fetch請求

在 chrome 瀏覽器中已經全域性支援了 fetch 函式,開啟除錯工具,在 console 中可以進行體驗下fetch。先不考慮跨域請求的使用方法,我們先請求同域的資源。例如 fetch then function response 使用 fetch 的建構函式請求資料後,返回乙個 promis...