7

jQuery ajax、axios、fetch 比較

 2 years ago
source link: https://kim85326.github.io/2019/11/01/jQuery-ajax-axios-fetch-%E6%AF%94%E8%BC%83/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

jQuery ajax、axios、fetch 比較


jQuery ajax

$.ajax({
  type: "POST",
  url: url,
  data: data,
  dataType: dataType,
  success: function() {},
  error: function() {},
});
  • 對原生 XHR 的封裝
  • 支援 JSONP
  • 缺點
    • 不太符合前端 MVVM 架構
    • 整包太大,只是要一個 ajax 方法,卻要引入整個 jQuery

axios

axios({
  method: "post",
  url: "/user/12345",
  data: {
    firstName: "Fred",
    lastName: "Flintstone",
  },
})
  .then(function(response) {
    console.log(response);
  })
  .catch(function(error) {
    console.log(error);
  });
  • 對原生 XHR 的封裝,且支援 Promise
  • Vue、React 都推薦使用
  • 支援瀏覽器和 NodeJS
  • 支援防止 CSRF
  • 支援取消請求
  • 支援攔截請求與回應

fetch

async function () {
	try {
	  const response = await fetch(url);
	  const data = response.json();
	  console.log(data);
	} catch(e) {
	  console.log("error", e);
	}
}
  • 新的原生 JavaScript 語法,要兼容舊的必須使用 polyfill
  • 解決 callback hell
  • 基於 Promise 實現,支援 async/await
  • 更加底層,有豐富的 API (Request、Response)
  • 脫離 XHR,將來有可能會取而代之
  • 缺點
    • 只對網路或跨網域噴錯,對 4xx、5xx 都當做成功的請求,需要封裝去處理
    • 需要設定 credentials 才能從服務端傳送或接收任何 cookies
    • 不支援 timeout
      • 使用 setTimeout 及 Promise.reject 的實現的超時控制,並不能阻止請求過程繼續在後台運行,造成了流量的浪費
    • 沒有辦法原生監測請求的進度,而 XHR 可以

Similar Posts

上一篇 axios


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK