reqwest與fetch的使用


reqwest的使用

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

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

It's AJAX
All over again. Includes support for xmlHttpRequest, JSONP, CORS, and CommonJS Promises A.

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

// 普通請求
reqwest({
    url: 'path/to/json'
  , type: 'json'
  , method: 'post'
  , data: { foo: 'bar', baz: 100 }        // 入參
  , error: function (err) { }
  , success: function (resp) {
      qwery('#content').html(resp.content)
    }
})

// jsonp請求
reqwest({
    url: 'path/to/json'
  , type: 'jsonp'
  , method: 'get'                    // jsonp請求,method可不寫,寫成post,依然會被瀏覽器默認為get
  , error: function (err) { }
  , success: function (resp) {
      qwery('#content').html(resp.content)
    }
})

// cors請求
reqwest({
    url: 'path/to/json'
  , type: 'json'
  , method: 'post'
  , contentType: 'application/x-www-form-urlencoded'
  , crossOrigin: true                  // cors跨域,服務端與客戶端存在cookie等數據憑證交互時需要設置crossOrigin,withCredentials
  , withCredentials: true
  , error: function (err) { }
  , success: function (resp) {
      qwery('#content').html(resp.content)
    }
})

// promise寫法
reqwest({
    url: 'path/to/data.jsonp?foo=bar'
  , type: 'jsonp'
  , jsonpCallback: 'foo'
})
  .then(function (resp) {
    qwery('#content').html(resp.content)
  }, function (err, msg) {
    qwery('#errors').html(msg)
  })
  .always(function (resp) {
    qwery('#hide-this').hide()
  })

fetch的使用

// 請求html 
fetch('/users.html')
  .then(function(response) {
    return response.text()              // 將內容將化成字符串類型數據
  }).then(function(body) {
    document.body.innerHTML = body
  })

// 提交json數據
fetch('/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({                // fetch的入參數據跟reqwest的data不太一樣,是body
    name: 'Hubot',
    login: 'hubot',
  })
})

// cors請求
fetch('https://example.com:1234/users', {
  mode: "cors",                       // 設置為支持跨域請求
  credentials: 'include'              // 設置允許發送相關憑證
})

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) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM