fetch 原生js api 使用范例
FETCH 基本用法:
fetch("请求的url地址")
.then(response => res.json() )
.then(data => console.log(data))
// 注意: 第一个.then 中获取到的不是最终数据,而是一个中间的数据流对象;
// 注意: 第一个 .then 中获取到的数据, 是一个 Response 类型对象;
// 注意: 第二个 .then 中,获取到的才是真正的 数据;GET:
// 默认 fetch("url") 的话, 发起的是 Get 请求
fetch("url")
.then(response => {
// 这个 response 就是 服务器返回的可读数据流, 内部存储的是二进制数据
// .json() 的作用,就是 读取 response 这个二进制数据流,并把 读取到的数
// 据,转为 JSON 格式的Promise 对象
return response.json()
})
.then(data => {
//这离 第二个 .then 中拿到的 data, 就是最终的数据
console.log(data)
})POST:
var sendData = new URLSearchParams()
sendData.append("goods_id",'32')
sendData.append("goods_name", 'banner')
var myHeaders = new Headers({
'Access-Control-Allow-Origin': '*',
'Content-Type': 'text/plain',
'token':'tk123'
});
fetch("url", {
method: "post",
headers: myHeaders, //headers
body: sendData //要发给服务器的数据
})
.then(response => response.json())
.then(data => console.log(data))