一、fetch请求的特点
- 服务器只要有返回结果,不论HTTP状态码是多少,promise实例都是fulfilled
- fetch 不会发送 cookies。除非你使用了credentials 的初始化选项。
- 通过网络获取一个 JSON 文件并将其打印到控制台。最简单的用法是只提供一个参数用来指明想 fetch() 到的资源路径,然后返回一个包含响应结果的promise(一个 Response 对象)。
当然它只是一个 HTTP 响应,而不是真的JSON。为了获取JSON的内容,我们需要使用 json() (en-US) 方法
fetch("/user/list").then((response)=>{
console.log(response)
})
每一次fetch请求也会返回一个promise实例:
实例成功:服务器只要有返回结果,不论HTTP状态码是多少,promise实例都是fulfilled
response.body存储的是响应主体信息「ReadableStream」
+ arrayBuffer
+ blob
+ json
+ text
+ …
执行这些方法是把服务器返回的响应主体信息变为指定格式的数据:返回值是一个新的promise实例,用来管控转换数据的过程是否成功
实例失败:服务器没有返回任何的结果「例如超时、中断请求、断网…」
fetch("/user/list").then((response)=>{
let {
status, statusText } = response;
if (status >= 200 && status < 400) {
// 成功
return response.json();
}
// 失败
return Promise.reject({
code: "status error",
status,
statusText,
});
})
.then((value) => {
console.log(value);
})
.catch((reason) => {
// 失败的统一处理
console.log(reason);
});
二、支持的请求参数
{
body: "xxx=xxx", //设置请求主体信息 「必须是POST系列请求 & 必须设置对应的Content-Type值」
cache: "no-cache",
credentials: "include",
headers: {
//自定义请求头信息
"content-type"