fetch的用法


fetch是web提供的一個可以獲取異步資源的api,目前還沒有被所有瀏覽器支持,它提供的api返回的是Promise對象,所以你在了解這個api前首先得了解Promise的用法。

參考:阮老師的文章 ,另外也可查看我的轉載:Promise 對象  (由於很多公司內網,對部分網站進行了過濾、封鎖,導致文章或文章圖片無法查看)

那我們首先講講在沒有fetch的時候,我們是如何獲取異步資源的:

//發送一個get請求是這樣的:

//首先實例化一個XMLHttpRequest對象
var httpRequest = new XMLHttpRequest();

//注冊httpRequest.readyState改變時會回調的函數,httpRequest.
//readyState共有5個可能的值,
//0 UNSENT (未打開) open()方法還未被調用;
//1 OPENED (未發送) send()方法還未被調用;
//2 HEADERS_RECEIVED (已獲取響應頭) send()方法已經被調用, 響應頭和響應狀態已經返回;
//3 LOADING (正在下載響應體) 響應體下載中; responseText中已經獲取了部分數據;
//4 DONE (請求完成) 整個請求過程已經完畢.
httpRequest.onreadystatechange = function(){
 //該回調函數會被依次調用4次
 console.log(httpRequest.readyState);

 if(httpRequest.readyState===4){
   //請求已完成
   if(httpRequest.status===200){
     //http狀態為200
     console.log(httpRequest.response);

     var data = JSON.parse(httpRequest.response);
     console.log(data);
   }
 }

}

//請求的網址
var url = "http://127.0.0.1:7777/list";
//該方法為初始化請求,第一個參數是請求的方法,比如GET,POST,PUT,第二個參數是請求的url
httpRequest.open('GET',url,true);

//設置http請求頭
httpRequest.setRequestHeader("Content-Type","application/json");

//發出請求,參數為要發送的body體,如果是GET方法的話,一般無需發送body,設為空就可以
httpRequest.send(null);

關於XMLHttpRequest的更多用法請參照:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest#open()

如果用了fetch之后,發送一個get請求是這樣的:

//請求的網址
var url = "http://127.0.0.1:7777/list";
//發起get請求
var promise = fetch(url).then(function(response) {

   //response.status表示響應的http狀態碼
   if(response.status === 200){
     //json是返回的response提供的一個方法,會把返回的json字符串反序列化成對象,也被包裝成一個Promise了
     return response.json();
   }else{
     return {}
   }

});
    
promise = promise.then(function(data){
  //響應的內容
	console.log(data);
}).catch(function(err){
	console.log(err);
})

接下來介紹下fetch的語法:

/**
參數:
input:定義要獲取的資源。可能的值是:一個URL或者一個Request對象。
init:可選,是一個對象,參數有:
	method: 請求使用的方法,如 GET、POST。
	headers: 請求的頭信息,形式為 Headers 對象或 ByteString。
	body: 請求的 body 信息:可能是一個 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 對象。注意 GET  HEAD 方法的請求不能包含 body 信息。
	mode: 請求的模式,如 cors、 no-cors 或者 same-origin,默認為no-cors,該模式允許來自 CDN 的腳本、其他域的圖片和其他一些跨域資源,但是首先有個前提條件,就是請求的 method 只能是HEAD、GET  POST。此外,如果 ServiceWorkers 攔截了這些請求,它不能隨意添加或者修改除這些之外 Header 屬性。第三,JS 不能訪問 Response 對象中的任何屬性,這確保了跨域時 ServiceWorkers 的安全和隱私信息泄漏問題。cors模式允許跨域請求,same-origin模式對於跨域的請求,將返回一個 error,這樣確保所有的請求遵守同源策略。
	credentials: 請求的 credentials,如 omit、same-origin 或者 include。
	cache:  請求的 cache 模式: default, no-store, reload, no-cache, force-cache, or only-if-cached.
返回值:一個 Promise,resolve 時回傳 Response 對象。
*/
fetch(input, init).then(function(response) {  });

一個發送post請求的示例:

fetch("http://127.0.0.1:7777/postContent", {
  method: "POST",
  headers: {
      "Content-Type": "application/json",
  },
  mode: "cors",
  body: JSON.stringify({
      content: "留言內容"
  })
}).then(function(res) {
  if (res.status === 200) {
      return res.json()
  } else {
      return Promise.reject(res.json())
  }
}).then(function(data) {
  console.log(data);
}).catch(function(err) {
  console.log(err);
});

如果考慮低版本瀏覽器的問題的話,引入https://github.com/github/fetch/blob/master/fetch.js 即可兼容。

 

出處:https://www.cnblogs.com/chris-oil/p/8430447.html

=======================================================================================

使用 Fetch

Fetch API 提供了一個 JavaScript 接口,用於訪問和操縱 HTTP 管道的一些具體部分,例如請求和響應。它還提供了一個全局 fetch() 方法,該方法提供了一種簡單,合理的方式來跨網絡異步獲取資源。

這種功能以前是使用 XMLHttpRequest 實現的。Fetch 提供了一個更理想的替代方案,可以很容易地被其他技術使用,例如  Service Workers。Fetch 還提供了專門的邏輯空間來定義其他與 HTTP 相關的概念,例如 CORS 和 HTTP 的擴展。

請注意,fetch 規范與 jQuery.ajax() 主要有三種方式的不同:

  • 當接收到一個代表錯誤的 HTTP 狀態碼時,從 fetch() 返回的 Promise 不會被標記為 reject, 即使響應的 HTTP 狀態碼是 404 或 500。相反,它會將 Promise 狀態標記為 resolve (但是會將 resolve 的返回值的 ok 屬性設置為 false ),僅當網絡故障時或請求被阻止時,才會標記為 reject。
  • fetch() 可以不會接受跨域 cookies;你也可以不能使用 fetch() 建立起跨域會話。其他網站的 Set-Cookie 頭部字段將會被無視。
  • fetch 不會發送 cookies。除非你使用了credentials初始化選項。(自 2017 年 8 月 25 日以后,默認的 credentials 政策變更為 same-origin。Firefox 也在 61.0b13 版本中進行了修改)

一個基本的 fetch 請求設置起來很簡單。看看下面的代碼:

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

這里我們通過網絡獲取一個 JSON 文件並將其打印到控制台。最簡單的用法是只提供一個參數用來指明想 fetch() 到的資源路徑,然后返回一個包含響應結果的promise(一個 Response 對象)。

當然它只是一個 HTTP 響應,而不是真的JSON。為了獲取JSON的內容,我們需要使用 json() 方法(在 Body mixin 中定義,被 RequestResponse 對象實現)。

注意:Body mixin 還有其他相似的方法,用於獲取其他類型的內容。參考 Body

最好使用符合內容安全策略 (CSP)的鏈接而不是使用直接指向資源地址的方式來進行Fetch的請求。

支持的請求參數

fetch() 接受第二個可選參數,一個可以控制不同配置的 init 對象:

參考 fetch(),查看所有可選的配置和更多描述。

// Example POST method implementation:

postData('http://example.com/answer', {answer: 42})
  .then(data => console.log(data)) // JSON from `response.json()` call
  .catch(error => console.error(error))

function postData(url, data) {
  // Default options are marked with *
  return fetch(url, {
    body: JSON.stringify(data), // must match 'Content-Type' header
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, same-origin, *omit
    headers: {
      'user-agent': 'Mozilla/4.0 MDN Example',
      'content-type': 'application/json'
    },
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, cors, *same-origin
    redirect: 'follow', // manual, *follow, error
    referrer: 'no-referrer', // *client, no-referrer
  })
  .then(response => response.json()) // parses response to JSON
}

發送帶憑據的請求

為了讓瀏覽器發送包含憑據的請求(即使是跨域源),要將credentials: 'include'添加到傳遞給 fetch()方法的init對象。

fetch('https://example.com', {
  credentials: 'include'
})

如果你只想在請求URL與調用腳本位於同一起源處時發送憑據,請添加 credentials: 'same-origin'

// The calling script is on the origin 'https://example.com'

fetch('https://example.com', {
  credentials: 'same-origin'
})

要改為確保瀏覽器不在請求中包含憑據,請使用 credentials: 'omit'

fetch('https://example.com', {
  credentials: 'omit'
})

上傳 JSON 數據

使用 fetch() POST JSON數據

var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers: new Headers({
    'Content-Type': 'application/json'
  })
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

上傳文件

可以通過 HTML <input type="file" /> 元素,FormData()fetch() 上傳文件。

var formData = new FormData();
var fileField = document.querySelector("input[type='file']");

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

上傳多個文件

可以通過HTML <input type="file" mutiple/> 元素,FormData()fetch() 上傳文件。

var formData = new FormData();
var photos = document.querySelector("input[type='file'][multiple]");

formData.append('title', 'My Vegas Vacation');
// formData 只接受文件、Blob 或字符串,不能直接傳遞數組,所以必須循環嵌入
for (let i = 0; i < photos.files.length; i++) {
    formData.append('photo', photos.files[i]);
}

fetch('https://example.com/posts', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

檢測請求是否成功

如果遇到網絡故障,fetch() promise 將會 reject,帶上一個 TypeError 對象。雖然這個情況經常是遇到了權限問題或類似問題——比如 404 不是一個網絡故障。想要精確的判斷 fetch() 是否成功,需要包含 promise resolved 的情況,此時再判斷 Response.ok 是不是為 true。類似以下代碼:

fetch('flowers.jpg').then(function(response) {
  if(response.ok) {
    return response.blob();
  }
  throw new Error('Network response was not ok.');
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
}).catch(function(error) {
  console.log('There has been a problem with your fetch operation: ', error.message);
});

自定義請求對象

除了傳給 fetch() 一個資源的地址,你還可以通過使用 Request() 構造函數來創建一個 request 對象,然后再作為參數傳給 fetch()

var myHeaders = new Headers();

var myInit = { method: 'GET',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default' };

var myRequest = new Request('flowers.jpg', myInit);

fetch(myRequest).then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

Request()fetch() 接受同樣的參數。你甚至可以傳入一個已存在的 request 對象來創造一個拷貝:

var anotherRequest = new Request(myRequest,myInit);

這個很有用,因為 request 和 response bodies 只能被使用一次(譯者注:這里的意思是因為設計成了 stream 的方式,所以它們只能被讀取一次)。創建一個拷貝就可以再次使用 request/response 了,當然也可以使用不同的 init 參數。

注意clone() 方法也可以用於創建一個拷貝。它和上述方法一樣,如果 request 或 response 的 body 已經被讀取過,那么將執行失敗。區別在於, clone() 出的 body 被讀取不會導致原 body 被標記為已讀取。

Headers

使用 Headers 的接口,你可以通過 Headers() 構造函數來創建一個你自己的 headers 對象。一個 headers 對象是一個簡單的多名值對:

var content = "Hello World";
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");

也可以傳一個多維數組或者對象字面量:

myHeaders = new Headers({
  "Content-Type": "text/plain",
  "Content-Length": content.length.toString(),
  "X-Custom-Header": "ProcessThisImmediately",
});

它的內容可以被獲取:

console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false
myHeaders.set("Content-Type", "text/html");
myHeaders.append("X-Custom-Header", "AnotherValue");

console.log(myHeaders.get("Content-Length")); // 11
console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]

myHeaders.delete("X-Custom-Header");
console.log(myHeaders.getAll("X-Custom-Header")); // [ ]

雖然一些操作只能在 ServiceWorkers 中使用,但是它提供了更方便的操作 Headers 的 API。

如果使用了一個不合法的HTTP Header屬性名,那么Headers的方法通常都拋出 TypeError 異常。如果不小心寫入了一個不可寫的屬性,也會拋出一個 TypeError 異常。除此以外的情況,失敗了並不拋出異常。例如:

var myResponse = Response.error();
try {
  myResponse.headers.set("Origin", "http://mybank.com");
} catch(e) {
  console.log("Cannot pretend to be a bank!");
}

最好在在使用之前檢查內容類型 content-type 是否正確,比如:

fetch(myRequest).then(function(response) {
  if(response.headers.get("content-type") === "application/json") {
    return response.json().then(function(json) {
      // process your JSON further
    });
  } else {
    console.log("Oops, we haven't got JSON!");
  }
});

Guard

由於 Headers 可以在 request 請求中被發送或者在 response 請求中被接收,並且規定了哪些參數是可寫的,Headers 對象有一個特殊的 guard 屬性。這個屬性沒有暴露給 Web,但是它影響到哪些內容可以在 Headers 對象中被操作。

可能的值如下:

  • none:默認的
  • request:從 request 中獲得的 headers(Request.headers)只讀
  • request-no-cors:從不同域(Request.mode no-cors)的 request 中獲得的 headers 只讀
  • response:從 response 中獲得的 headers(Response.headers)只讀
  • immutable:在 ServiceWorkers 中最常用的,所有的 headers 都只讀。

注意:你不可以添加或者修改一個 guard 屬性是 request 的 Request Header 的 Content-Length 屬性。同樣地,插入 Set-Cookie 屬性到一個 response header 是不允許的,因此,Service Worker 中,不能給合成的 Response 的 header 添加一些 cookie。

Response 對象

如上所述,Response 實例是在 fetch() 處理完 promise 之后返回的。

你會用到的最常見的 response 屬性有:

  • Response.status — 整數(默認值為200)為response的狀態碼。
  • Response.statusText — 字符串(默認值為"OK"),該值與 HTTP 狀態碼消息對應。
  • Response.ok — 如上所示,該屬性是來檢查response的狀態是否在 200 - 299(包括200 和 299)這個范圍內。該屬性返回一個布爾值

它的實例也可用通過 JavaScript 來創建,但只有在 ServiceWorkers 中才真正有用,當使用 respondWith() 方法並提供了一個自定義的 response 來接受 request 時:

var myBody = new Blob();

addEventListener('fetch', function(event) {
  event.respondWith(new Response(myBody, {
    headers: { "Content-Type" : "text/plain" }
  });
});

Response() 構造方法接受兩個可選參數—— response 的數據體和一個初始化對象(與Request() 所接受的 init 參數類似。)

注意: 靜態方法 error() 只是返回了錯誤的response。與此類似地,redirect() 只是返回了一個可以重定向至某 URL 的 response。這些也只與 Service Worker 有關。

Body

不管是請求還是響應都能夠包含 body 對象。body 也可以是以下任意類型的實例。

Body 類定義了以下方法(這些方法都被 RequestResponse所實現)以獲取 body 內容。這些方法都會返回一個被解析后的Promise對象和數據。

比起XHR來,這些方法讓非文本化的數據使用起來更加簡單。

請求體可以由傳入 body 參數來進行設置:

var form = new FormData(document.getElementById('login-form'));
fetch("/login", {
  method: "POST",
  body: form
})

request和response(包括 fetch() 方法)都會試着自動設置 Content-Type。如果沒有設置 Content-Type 值,發送的請求也會自動設值。

特性檢測

Fetch API 的支持情況,可以通過檢測Headers, Request, Responsefetch()是否在WindowWorker 域中。例如:

if(self.fetch) {
    // run my fetch request here
} else {
    // do something with XMLHttpRequest?
}

Polyfill

如果要在不支持的瀏覽器中使用 Fetch,可以使用 Fetch Polyfill

規范

詳細說明 狀態 注釋
Fetch Living Standard Initial definition

瀏覽器兼容性

Report problems with this compatibility data on GitHub

  desktop mobile
  Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox Android Opera Android iOS Safari Samsung Internet
fetch
Experimental
ChromeFull support42
 
EdgeFull support14
 
FirefoxFull support39
 
Internet ExplorerNo supportNo
 
OperaFull support29
 
SafariFull support10.1
 
WebView AndroidFull support42
 
Chrome AndroidFull support42
 
Firefox AndroidFull support39
 
Opera AndroidFull support29
 
iOS SafariFull support10.3
 
Samsung InternetFull support4.0
 
Support for blob: and data:
Experimental
ChromeFull support48
 
EdgeFull support79
 
FirefoxCompatibility unknown; please update this.?
 
Internet ExplorerNo supportNo
 
OperaCompatibility unknown; please update this.?
 
SafariCompatibility unknown; please update this.?
 
WebView AndroidFull support43
 
Chrome AndroidFull support48
 
Firefox AndroidCompatibility unknown; please update this.?
 
Opera AndroidCompatibility unknown; please update this.?
 
iOS SafariCompatibility unknown; please update this.?
 
Samsung InternetFull support5.0
 
referrerPolicy
ChromeFull support52
 
EdgeFull support79
 
FirefoxFull support52
 
Internet ExplorerNo supportNo
 
OperaFull support39
 
SafariFull support11.1
 
WebView AndroidFull support52
 
Chrome AndroidFull support52
 
Firefox AndroidFull support52
 
Opera AndroidFull support41
 
iOS SafariNo supportNo
 
Samsung InternetFull support6.0
 
signal
Experimental
ChromeFull support66
 
EdgeFull support16
 
FirefoxFull support57
 
Internet ExplorerNo supportNo
 
OperaFull support53
 
SafariFull support11.1
 
WebView AndroidFull support66
 
Chrome AndroidFull support66
 
Firefox AndroidFull support57
 
Opera AndroidFull support47
 
iOS SafariFull support11.3
 
Samsung InternetFull support9.0
 
Streaming response body
Experimental
ChromeFull support43
 
EdgeFull support14
 
FirefoxFull supportYes
disabled
Internet ExplorerNo supportNo
 
OperaFull support29
 
SafariFull support10.1
 
WebView AndroidFull support43
 
Chrome AndroidFull support43
 
Firefox AndroidNo supportNo
 
Opera AndroidNo supportNo
 
iOS SafariFull support10.3
 
Samsung InternetFull support4.0
 

Legend

Full supportFull support
No supportNo support
Compatibility unknownCompatibility unknown
Experimental. Expect behavior to change in the future.
See implementation notes.
User must explicitly enable this feature.

參見

 

出處:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

=======================================================================================

Fetch使用方法

前言:

  fetch是用來取代傳統的XMLHttpRequest的。 它的優點很多,包括鏈式調用的語法、返回promise等。

 

什么是fetch?

  fetch api是基於promise的設計,它是為了取代傳統xhr的不合理的寫法而生的。

 

WHY fetch?

  xhr請求寫起來非常的混亂,如下所示:

復制代碼
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';

xhr.onload = function() {
  console.log(xhr.response);
};

xhr.onerror = function() {
  console.log("Oops, error");
};

xhr.send();
復制代碼

  

  但是使用fetch之后,如下所示:

復制代碼
fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function(e) {
  console.log("Oops, error");
});
復制代碼

  這種鏈式調用的風格看上去會非常舒服。

 

  如果我們再使用了箭頭函數就會更加簡潔了。 

fetch(url).then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.log("Oops, error", e))

  

  通過使用fetch api,可以將傳統的xhr的粗糙的使用方法轉化的如此精簡,實在是好! 

 

  但是呢? 使用Promise,還是可以很明顯看到callback的使用,不急,我們還可以使用 async、await :

復制代碼
// Async/Await requirements: Latest Chrome/FF browser or Babel: https://babeljs.io/docs/plugins/transform-async-to-generator/
// Fetch requirements: Latest Chrome/FF browser or Github fetch polyfill: https://github.com/github/fetch

// async function
async function fetchAsync () {
  // await response of fetch call
  let response = await fetch('https://api.github.com');
  // only proceed once promise is resolved
  let data = await response.json();
  // only proceed once second promise is resolved
  return data;
}

// trigger async function
// log response or catch error of fetch promise
fetchAsync()
    .then(data => console.log(data))
    .catch(reason => console.log(reason.message))
復制代碼

  這樣看上去是不是就好多了呢?

注意: 對於async和await的使用還是很明確的,就是一般我們在一個異步函數之前添加 await 關鍵詞,然后在這個 await 的相關代碼外面使用的時 async 函數,這樣的結合才是合適的。

利用 async 和 await,我們就可以像寫同步代碼一樣來寫異步代碼啦! 

但是呢,目前async 和 await 的支持性還不是很好,目前還無法在一般的瀏覽器中使用!

   

 

 

 

 

 

 

 

 

 

  

基本使用方法:

fetch必須接受一個資源路徑作為參數,並且返回了一個promise,所以我們可以直接使用鏈式調用的方式。 

復制代碼
 fetch("/getAllProduct").then(function(res) {
            return res.json();
        }).then(function (data) {
            if (data.code == 200) {
              console.log('獲取到所有產品' ,data.data);
              that.props.addAllProduct(data.data);
            } else {
              console.log(data.message);
            }
        })
復制代碼

這樣,我們就可以發送一個ajax請求。

復制代碼
/* 對客戶端的返回數據封裝
 * @param [code] (number) code為返回的狀態碼
 * @param [message] (string) message為返回的信息
 * @param [data] (any) data是可選的,為返回給前端的數據
 */
// 注意: retrunJson中的res為node處理接口的回調函數中的res,這個是必須的。
function returnJson(res, code, message, data) {
    var response = {
        code: code,
        message: message
    };
    if (typeof data !== 'undefined') {
        response.data = data;
    }
    res.json(response);
   // 返回這個請求之后,必須要 res.end()表示請求的結束,否則后台可能會崩潰。 res.end(); } router.post(
'/register', function (req, res) { let userName = req.body.username, password = req.body.password, passwordAgain = req.body.passwordAgain, type = req.body.type; console.log(userName, password, type); if (type == 1) { if (password == passwordAgain) { let managerId = uuidv1(); console.log(userName, password, passwordAgain); var newUser = new Manager({ name: userName, password: password, type: req.body.type, managerId: managerId }); Manager.find(userName, function (err, user) { if (err) { returnJson(res, 5001, '服務器錯誤,注冊失敗'); } else { if (user !== null) { returnJson(res, 4003, "此用戶已經注冊!"); } else { // 如果符合條件,就注冊該用戶,將數據保存在數據庫。 newUser.save(function (err, user) { if (err) { // 服務器端錯誤,失敗返回狀態碼500 returnJson(res, 500, "用戶注冊失敗!"); } else { // user數據較簡單,直接傳遞user即可,如果復雜,我們可以考慮使用對象形式傳遞更多數據。 returnJson(res, 200, "用戶注冊成功!", user); } }); } } }); } else { returnJson(res, 4001, "用戶兩次輸入密碼不一致!"); } } else if( type == 2) { if (password == passwordAgain) { let userId = uuidv1(); console.log(userName, password, passwordAgain); var newUser = new User({ name: userName, password: password, type: req.body.type, userId: userId }); User.find(userName, function (err, user) { if (err) { returnJson(res, 5001, '服務器錯誤,注冊失敗'); } else { if (user !== null) { returnJson(res, 4003, "此用戶已經注冊!"); } else { // 如果符合條件,就注冊該用戶,將數據保存在數據庫。 newUser.save(function (err, user) { if (err) { // 服務器端錯誤,失敗返回狀態碼500 returnJson(res, 500, "用戶注冊失敗!"); } else { // user數據較簡單,直接傳遞user即可,如果復雜,我們可以考慮使用對象形式傳遞更多數據。 returnJson(res, 200, "用戶注冊成功!", user); } }); } } }); } else { returnJson(res, 4001, "用戶兩次輸入密碼不一致!"); } } });
復制代碼

這樣,我們就可以處理一個ajax請求。

 

注意點:

1、fetch() 返回的是一個Promise對象。

  fetch使用的promise對象可以使得我們使用同步的方式寫異步函數。

 

2、 fetch api是可以結合 async 和 await 來使用的。 

  fetch是基於promise實現的,但是使用promise的寫法,我們還是可以看到callback的影子,如果結合 async和await來使用,還是非常不錯的。

 

3、 Fetch api 提供的spi囊括但是不限於xhr的所有功能。

 

4、 fetch api 可以跨域。 

  參考: https://fetch.spec.whatwg.org/#http-cors-protocol

  跨域請求必須包括  Origin 作為header. 

     以上。

    我們在發送fetch請求的時候就會使用到CORS協議,盡管這些對於開發者來說是透明的,但是瀏覽器還是會發送 origin 字段。 

              那么,這里推薦自己用 fecth 嗎?實際上,因為我不太信任它,原因有很多。因此我在用一個叫 axios 的庫,也是基於 promise 的,同時非常可靠。

 

5、fetch提供了對request和response對象的通用定義。

  Fetch 提供了對 Request 和 Response (以及其他與網絡請求有關的)對象的通用定義。所以在一個Fetch請求中,完全可以只使用Request 和 Response兩個對象,通過Request 設置參數,通過Response 對返回值進行處理。 

 所以,我們可以將一個fetch定義如下:

復制代碼
var myHeaders = new Headers();
myHeaders.append('Content-Type', 'image/jpeg');
var option = { method: 'GET',
    headers: myHeaders,
    mode: 'cors',
    cache: 'default' };
var myRequest = new Request('https://api.github.com/users/mzabriskie',option);
fetch(myRequest).then(function(response) {
    ... 
});
復制代碼

   

參考文章: https://github.com/camsong/blog/issues/2

 

出處:https://www.cnblogs.com/zhuzhenwei918/p/7249691.html


免責聲明!

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



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