whatwg-fetch 基于 promise 可以实现浏览器的网络请求,它参照了 WHATWG Fetch standard,使用 fetch()
替代传统网络的 XMLHttpRequest。axios 的拆包后体积是 1.7M,而 whatwg-fetch 的拆包体积只有 54K,显然,只在浏览器进行网络通信的场景可以使用 whatwg-fetch 。
Fetch
whatwg-fetch 用于浏览器的网络请求,可以结合 express 创建一个网络请求的例子
使用 npm init -y
创建环境,安装 express,新建 server.js 文件,代码如下。创建 app,配置跨域,创建一个 /test
路径 post
方法的接口,用户请求后返回信息,监听3000端口。
const express = require("express");
const app = express();
app.all("*", (_, res, next) => { // 支持跨域
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*");
res.header("Access-Control-Allow-Headers", "X-Requestd-with");
res.header("Access-Control-Allow-Headers", "Content-Type");
next();
});
app.post("/test", (req, res) => {
console.log("🚀 ~ file: index.js:14 ~ app.post ~ req:", req.headers.host);
res.send("hello,fetch");
});
app.listen(3000, () => {
console.log("listen 3000");
});
创建一个浏览器运行的 html 文件,代码如下。配置 whatwg-fetch 的 cdn,使用 fetch 方法请求 express 创建的接口,通过 response.text() 即可获取返回的内容。
<script src="https://cdn.jsdelivr.net/npm/whatwg-fetch@3.6.2/dist/fetch.umd.min.js"></script>
<script>
fetch("http://localhost:3000/test", {
method: "POST",
body: JSON.stringify({ name: "leon" }),
headers: {
"Content-Type": "application/json",
},
credentials: "same-origin",
}).then(
async function (response) {
const text = await response.text();
console.log("🚀 ~ file: whatwg-fetch.html:13 ~ text:", text);
},
function (error) {
console.log(error.message);
}
);
</script>
Request
可以通过 fetch() 方法实现 http 请求,调用的时候不需要手动构造,内部已经进行实例化。
如上面的例子,fetch 函数可以传入两个参数,url 和 options。url 可以使用绝对地址,不包含 host,如果有 host 就需要进行跨域处理,上面的例子中就是通过设置响应头实现了跨域。
一个请求还可以使用其他实例化请求作为参数而不是 url,这样这个请求就会从其他实例化请求中继承 url 和 options。
options 包括 method,body,headers,credentials。
- method(String),http 请求方法,默认是 GET
- headers(Object),默认是 {}
- credentials(String),权限认证模式。不包含权限认证使用 omit,同站点的认证使用 same-site,所有站点都需要认证使用 include。
- body,下面介绍了 body 的类型
Class | Default Content-Type |
---|---|
String | text/plain;charset=UTF-8 |
URLSearchParams | application/x-www-form-urlencoded;charset=UTF-8 |
FormData | multipart/form-data |
Blob | inherited from the blob.type property |
ArrayBuffer | |
TypedArray | |
DataView |
其他数据结构需要转化成上述形式才能够发送,比如可以使用 JSON.stringify(data)
来序列化数据转成 JSON 字符串。
小结
首先结合 whatwg-fetch 和 express 搭建了一个网络请求的例子,再详细介绍了请求参数。