javascript fetch 用法講解
fetch 的詳細(xì)講解
fetch 是一個現(xiàn)代化的 JavaScript API,用于發(fā)送網(wǎng)絡(luò)請求并獲取資源。它是瀏覽器提供的全局方法,可以替代傳統(tǒng)的 XMLHttpRequest。fetch 支持 Promise,因此更易用且代碼更清晰。
1. 基本語法
1.1 語法
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));參數(shù):
url:請求的資源地址。options:可選參數(shù),用于配置請求(如方法、頭部信息、請求體等)。
返回值:
- 一個
Promise,解析為Response對象。
1.2 示例:簡單 GET 請求
fetch('https://api.example.com/data')
.then(response => response.json()) // 將響應(yīng)解析為 JSON
.then(data => console.log(data)) // 輸出解析后的數(shù)據(jù)
.catch(error => console.error('Error:', error)); // 捕獲請求錯誤2. Response 對象
Response 對象表示 fetch 請求的結(jié)果,包含以下常用屬性和方法:
status:HTTP 狀態(tài)碼。
fetch('https://api.example.com')
.then(response => {
console.log(response.status); // 200, 404 等
});ok:布爾值,表示請求是否成功(狀態(tài)碼在 200-299 之間)。
fetch('https://api.example.com')
.then(response => {
if (response.ok) {
console.log('Request was successful');
} else {
console.error('Request failed');
}
});json():將響應(yīng)解析為 JSON。
fetch('https://api.example.com')
.then(response => response.json())
.then(data => console.log(data));text():將響應(yīng)解析為純文本。
fetch('https://api.example.com')
.then(response => response.text())
.then(data => console.log(data));headers:響應(yīng)頭部信息。
fetch('https://api.example.com')
.then(response => {
console.log(response.headers.get('Content-Type'));
});3. 配置請求
fetch 的第二個參數(shù) options 用于配置請求方法、頭部信息、請求體等。
3.1 常用配置
| 選項(xiàng) | 描述 | 示例值 |
|---|---|---|
method | HTTP 請求方法,默認(rèn)是 GET | GET, POST, PUT |
headers | 請求頭部信息,用于傳遞內(nèi)容類型或認(rèn)證信息 | { 'Content-Type': 'application/json' } |
body | 請求體,用于發(fā)送數(shù)據(jù)(POST 和 PUT 請求中使用) | JSON.stringify({...}) |
mode | 請求模式,默認(rèn)是 cors | cors, no-cors, same-origin |
credentials | 是否攜帶憑據(jù),如 cookies | same-origin, include |
cache | 緩存模式 | default, no-store, reload |
3.2 示例:POST 請求
發(fā)送一個包含 JSON 數(shù)據(jù)的 POST 請求:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'John Doe',
age: 30,
}),
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));3.3 示例:自定義請求頭
向 API 添加身份驗(yàn)證令牌:
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer YOUR_TOKEN',
},
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));4. 錯誤處理
fetch 的 Promise 只有在網(wǎng)絡(luò)錯誤時(shí)才會拒絕,比如斷網(wǎng)或無法解析域名。HTTP 錯誤狀態(tài)碼(如 404 或 500)不會自動觸發(fā) catch。
4.1 檢查響應(yīng)狀態(tài)
需要手動檢查 response.ok 或 response.status:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));5. 超時(shí)和取消請求
fetch 本身不支持超時(shí)或取消請求,可以通過 AbortController 實(shí)現(xiàn)。
5.1 設(shè)置請求超時(shí)
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 秒后中止請求
fetch('https://api.example.com/data', { signal: controller.signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.error('Fetch aborted!');
} else {
console.error('Error:', error);
}
});
// 清除超時(shí)
clearTimeout(timeoutId);6. CORS(跨域請求)
如果請求跨域資源,服務(wù)端需要設(shè)置 Access-Control-Allow-Origin 頭部。如果沒有配置,瀏覽器會拒絕跨域請求。
示例:配置 CORS
服務(wù)端需要添加類似以下的頭部信息:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
7. 與 Axios 的對比
fetch 和 Axios 都是常用的網(wǎng)絡(luò)請求工具,但有一些差異:
| 特性 | fetch | Axios |
|---|---|---|
| API 原生支持 | 內(nèi)置于瀏覽器,無需安裝額外庫 | 需要安裝第三方庫 |
| Promise 支持 | 原生支持 | 原生支持 |
| 默認(rèn)錯誤處理 | 只處理網(wǎng)絡(luò)錯誤,不自動處理 HTTP 錯誤狀態(tài) | 自動拋出 HTTP 錯誤 |
| 自動序列化 JSON | 需要手動解析響應(yīng)為 JSON | 自動解析 JSON 響應(yīng) |
| 支持取消請求 | 使用 AbortController 實(shí)現(xiàn) | 內(nèi)置取消功能 |
| 靈活性 | 標(biāo)準(zhǔn)化 API,更適合簡單場景 | 功能豐富,適合復(fù)雜場景 |
8. 高級用法
8.1 流式響應(yīng)(ReadableStream)
fetch 可以處理流式響應(yīng)(比如逐步加載大文件):
fetch('https://api.example.com/stream')
.then(response => response.body)
.then(stream => {
const reader = stream.getReader();
const decoder = new TextDecoder('utf-8');
reader.read().then(function processText({ done, value }) {
if (done) {
console.log('Stream finished');
return;
}
console.log(decoder.decode(value));
return reader.read().then(processText);
});
});9. 常見問題
9.1 CORS 錯誤
- 瀏覽器跨域請求時(shí),服務(wù)端未正確配置
CORS。 - 解決方案:
- 服務(wù)端設(shè)置
Access-Control-Allow-Origin。 - 使用代理服務(wù)器避免跨域。
- 服務(wù)端設(shè)置
9.2 網(wǎng)絡(luò)超時(shí)
fetch默認(rèn)沒有超時(shí),可以使用AbortController設(shè)置超時(shí)。
9.3 JSON 解析錯誤
如果 API 返回非 JSON 數(shù)據(jù),調(diào)用 response.json() 會報(bào)錯:
fetch('https://api.example.com/data')
.then(response => response.json())
.catch(error => console.error('Invalid JSON:', error));10. 總結(jié)
fetch 是一個強(qiáng)大且現(xiàn)代化的網(wǎng)絡(luò)請求工具,適合大部分 Web 開發(fā)場景:
- 優(yōu)點(diǎn):原生支持、Promise API、更清晰的語法。
- 缺點(diǎn):錯誤處理需要手動檢查、默認(rèn)不支持超時(shí)和取消。
對于簡單場景,fetch 是首選;對于更復(fù)雜的場景(如請求超時(shí)、豐富的配置需求),可以考慮使用 Axios 等第三方庫。
到此這篇關(guān)于javascript fetch 講解的文章就介紹到這了,更多相關(guān)javascript fetch內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于SpringCloud的微服務(wù)結(jié)構(gòu)及微服務(wù)遠(yuǎn)程調(diào)用
Spring Cloud 是一套完整的微服務(wù)解決方案,基于 Spring Boot 框架,準(zhǔn)確的說,它不是一個框架,而是一個大的容器,它將市面上較好的微服務(wù)框架集成進(jìn)來,從而簡化了開發(fā)者的代碼量,需要的朋友可以參考下2023-05-05
SpringBoot操作MaxComputer方式(保姆級教程)
這篇文章主要介紹了SpringBoot操作MaxComputer方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03
Java編程實(shí)現(xiàn)深度優(yōu)先遍歷與連通分量代碼示例
這篇文章主要介紹了Java編程實(shí)現(xiàn)深度優(yōu)先遍歷與連通分量代碼示例,2017-11-11
Spring-cloud Config Server的3種配置方式
這篇文章主要介紹了Spring-cloud Config Server的3種配置方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
Java中關(guān)于字典樹的算法實(shí)現(xiàn)
字典樹,又稱單詞查找樹,Trie樹,是一種樹形結(jié)構(gòu),哈希表的一個變種。用于統(tǒng)計(jì),排序和保存大量的字符串,本文針對字典樹給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值2021-09-09
SpringBoot如何對LocalDateTime進(jìn)行格式化并解析
這篇文章主要介紹了SpringBoot如何對LocalDateTime進(jìn)行格式化方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07

