這篇文章主要介紹JavaScript中使用Fetch()的案例,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
Fetch()提供了一種方式進行跨網絡異步請求資源的方式,用于訪問和操作HTTP管道的部分,比如:請求和相應。
接收到表示錯誤的HTTP狀態碼時,fetch()返回的Promise不會被標記為reject(即使狀態碼為404或500)。fetch()會將Promise狀態標記為resolve(但resolve返回值但OK 屬性設置為 false)。網絡故障或請求被阻止才會標記為reject。
fetch()不會從服務端發送或接收任何cookies。發送cookies 需要設置 fetch(url, {credentials: 'include'}) 選項。
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(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))獲取一個JSON文件,并打印到控制臺。指明資源路徑,然后返回一個Response對象,使用json()方法獲取JSON但內容。
fetch()接受第二個可選參數,控制不同配置的init參數。
// 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
}包含憑據的請求:
fetch('https://example.com', {
//將credentials: 'include'添加到傳遞給fetch()方法的init對象
credentials: 'include'
})若在同源櫥發送憑據:
fetch('https://example.com', {
credentials: 'same-origin'
})確保瀏覽器不在請求中包含憑據:
fetch('https://example.com', {
credentials: 'omit'
})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));使用 <input type="file" />、FormData() 和 fetch()
使用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");內容可被獲?。?/p>
console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false語法簡潔,更加語義化
基于標準 Promise 實現,支持 async/await
同構方便,使用 isomorphic-fetch
以上是JavaScript中使用Fetch()的案例的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。