# Fetch
# Fetch 是什么
Fetch 也是前后端通信的一种方式。
Fetch 是 Ajax (XMLHttpRequest) 的一种替代方案,它是基于 Promise 的。
Ajax 的兼容性比 Fetch 好。
Fetch 中目前还没有 abort,timeout,这些想要使用还要我们去实现。
# Fetch 的基本用法
| console.log(fetch) | 
效果:在 js 中是有 fetch 这个东西的

- Response {type: 'cors', url: 'http://127.0.0.1:81/data', redirected: false, status: 200, ok: true, …} body: ReadableStream bodyUsed: false headers: Headers {} ok: true redirected: false status: 200 statusText: "" type: "cors" url: "http://127.0.0.1:81/data" [[Prototype]]: Response
- body/bodyUsed:只能读一次,读过之后就不让再读了。 
- OK:如果 OK 为 true,表示可以读取数据,不用再去判断 HTTP 状态码了。 
| let url = 'http://127.0.0.1:81/data' | |
| fetch(url).then(response=>{ | |
| console.log(response) | |
| if(response.ok){ | |
| console.log(response.json()) | |
|    } | |
| }).catch(err=>{ | |
| console.log(err) | |
| }) | 
效果:返回了一个 Promise 对象,我们需要将他返回出去才能看到数据

| let url = 'http://127.0.0.1:81/data' | |
| fetch(url).then(response=>{ | |
| console.log(response) | |
| if(response.ok){ | |
| console.log(response.json()) | |
| return response.json() | |
|    } | |
| }).then(data=>{ | |
| console.log(data) | |
| }).catch(err=>{ | |
| console.log(err) | |
| }) | 
报错了,翻译一下:

类型错误:无法在“响应”上执行“json”:正文流已读取
取.html:16:29
原因是读取了两次,上面 body 明确不可以读取两次的只能读取一次
将返回值上面的 console.log 读取数据的给注释掉
| let url = 'http://127.0.0.1:81/data' | |
| fetch(url).then(response=>{ | |
| console.log(response) | |
| if(response.ok){ | |
|       // console.log(response.json()) | |
| return response.json() | |
|    } | |
| }).then(data=>{ | |
| console.log(data) | |
| }).catch(err=>{ | |
| console.log(err) | |
| }) | 
数据就读取出来了。

如果数据不是 JSON 格式的则使用 response.text () 来返回文本格式的数据:
| let url = 'http://127.0.0.1:81/data' | |
| fetch(url).then(response=>{ | |
| console.log(response) | |
| if(response.ok){ | |
|       // console.log(response.json()) | |
|       // return response.json() | |
| return response.text() | |
|    } | |
| }).then(data=>{ | |
| console.log(data) | |
| }).catch(err=>{ | |
| console.log(err) | |
| }) | 
效果:

# Fetch 第二个参数是对象,用来配置 Fetch。
| let url = 'http://127.0.0.1:81/json' | |
| fetch(url,{ | |
| method:'post', | |
| headers:{ | |
| 'Content-Type':'application/json' | |
| }, | |
|    //boey 发送请求体数据,发送 json 使用 body 直接传会报错 | |
|    // 直接传递对应的类型为 x-www-form-urlencoded | |
|    // body:null, | |
|    //body:'name = 张三 & amp;age=18', | |
|    // 不能直接传对象需要自己转 | |
| body:JSON.stringify({name:'张三',age:18}), | |
|    // 跨域资源共享,默认就是 cors | |
| mode:'cors', | |
|    // 跨域请求是否携带 Cooki, 传入的不再是布尔值 | |
| credentials:'include' | |
| }).then(response=>{ | |
| if(response.ok){ | |
| return response.json() | |
|    } | |
| }).then(data=>{ | |
| console.log(data) | |
| }).catch(err=>{ | |
| console.log(err) | |
| }) | 
效果:

