1.前言
1.之前寫了篇文章前端請求的5種方式
2.其中fetch
的方式應該還是 不熟悉
3.所以這篇文章詳細的梳理下fetch
2. 是什么
Fetch API 提供了一個
JavaScript 接口
骑疆,用于訪問和操縱HTTP 管道
的一些具體部分
例如請求和響應。它還提供了一個全局fetch()
方法,該方法提供了一種簡單全封,合理的方式來跨網絡異步獲取資源
活烙。
這種功能以前是使用
XMLHttpRequest
實現的。
Fetch
提供了一個更理想的替代方案,可以很容易地被其他技術使用馋评,
例如Service Workers
(en-US)诗芜。Fetch 還提供了專門的邏輯空間來定義其他與 HTTP 相關的概念瞳抓,
例如CORS
和HTTP
的擴展。
簡單總結的話 就是類似
axios
,使用Promise
語法,
但是瀏覽器原生支持,不需要下載第三方的文件
3. 基礎語法 get請求
3.1 簡要demo
let registerFn = () => {
fetch(`/getData?name=${userName.value}&password=${password.value}`).then(res => {
return res.json()
}).then(res => {
console.log("get 結果:", res)
}).catch(error => {
console.log("錯誤:", error)
})
}
3.2 簡要分析
- 默認是
get
請求
fetch()
2個參數
參數1: 服務器地址
參數2: 可選的 配置參數
HTTP 請求的方法伏恐、標頭孩哑、數據體都在這個對象里面設置
3.
fetch()
采用模塊化設計,API 分散在多個對象上(Response
對象翠桦、Request
對象横蜒、Headers
對象)
4.fetch()
使用Promise
,不使用回調函數销凑,因此大大簡化了寫法丛晌,寫起來更簡潔
5.response
是一個 Stream 對象
3. 配置參數
HTTP 請求的方法、標頭斗幼、數據體都在這個對象里面設置
{
body: JSON.stringify(data), //必須和'Content-Type' 匹配
cache: 'no-cache', // 是否需要緩存,可以的值, 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
}
3.1 credentials
include
瀏覽器發(fā)送 cookie(即使是跨域源也發(fā)送)
same-origin
和 腳本 同源 才發(fā)送cookie
omit
不使用cookie
3.2 第一個then
一般第一個
then
做一個數據的 格式化
例如: res.json()
4. post請求 常用配置
服務器 本地用
node
隨便寫的
下面是post
寫法
let loginFn = async () => {
let data = {
name: "yzs",
password: "123456"
}
try {
let res = await fetch("/login", {
method: "POST",
body:JSON.stringify(data)
}).then(res => res.json())
console.log("post 結果:", res)
} catch (error) {
// fetch 里面的 catch
console.log("error:", error)
}
}
5. post 單文件上傳
let upload = async () => {
let file = document.querySelector("input[type=file]").files[0];
// 表單數據對象
let formatData = new FormData()
// 第一個 key fileInfo
// 第二個value是對應的值 file
// 把上傳的內容添加到表單 數據對象里面
formatData.append("fileInfo", file)
try {
let res = await fetch("/myupload", {
method: "POST",
body: formatData
}).then(res => res.json())
showImg.src = res.path
console.log("成功:", res);
} catch (error) {
console.log("error", error)
}
}
6. post 多文件上傳配置
var formData = new FormData();
var photos = document.querySelector("input[type='file'][multiple]");
formData.append('title', 'My Vegas Vacation');
// formData 只接受文件澎蛛、Blob 或字符串,不能直接傳遞數組蜕窿,所以必須循環(huán)嵌入
for (let i = 0; i < photos.files.length; i++) {
formData.append('photo', photos.files[i]);
}
7. 重點 post 請求頭配置
post
的body
數據要和content-type
匹配不然請求不成功
7.1 json數據配置
const response = await fetch('/login', {
method: 'POST',
body: JSON.stringify({ name: "yzs尹",password:"123456" }),
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
})
7.2 key-value配置
const response = await fetch('/list', {
method: 'POST',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
},
body: 'name=yzs&password=123456'
})
7.3 表單配置
const form = document.querySelector('form');
const response = await fetch('/submit', {
method: 'POST',
body: new FormData(form)
})
7.4 上傳配置
const input = document.querySelector('input[type="file"]');
const data = new FormData();
data.append('file', input.files[0]);
//額外追加數據
data.append('name', 'yzs');
fetch('/upload', {
method: 'POST',
body: data
});
上傳 肯定得通過表單 ,所以其實和表單提交 差不多
7.4 二進制數據
做一些圖片的轉化 時會用到二進制上傳
let blob = await new Promise(resolve =>
canvasElem.toBlob(resolve, 'image/png')
);
let response = await fetch('/user/avatar', {
method: 'POST',
body:data
canvasElem
借助畫布的toBlob
功能
也可以使用畫布的toDataURL