fetch的使用:
1: 作用: fetch这个API ,是专门用来发起Ajax请求的
2: fetch是由 原生JS 提供的API, 专门用来取代 XHR 这个对象的
用法:
fetch('请求的url地址')
.then( response=>response.json() )
.then(data =>console.log(data) )
注意 :
第一个.then()中 获取到的不是最终数据,而是一个中间的数据流对象
第一个 .then 中获取到的数据 , 是一个 Response 类型的对象
//第二个 .then()中获取的 才是真正的数据
举例:
默认 fetch(‘url’)的话, 发起的是 Get请求
//这个 response 就是 服务器返回的可读数据流, 内部存储的是二进制数据
//.json()的作用,就是 读取response这个 二进制数据流 并把 读取到的数据, 转为JSON格式的 Promise 对象
fetch('http://39.106.32.91:3000/api/getlunbo').then(response => {
//这个 response 就是 服务器返回的可读数据流, 内部存储的是二进制数据
//.json()的作用,就是 读取response这个 二进制数据流 并把 读取到的数据, 转为JSON格式的 Promise 对象
return response.json()
}).then(data=>{
//这里,第二个.then中, 拿到的data,就是最终数据
console.log(data)
})
fetch发起 post请求:
//创建一个表单数据, 这个form 所对应的数据,会以Post形式 的 请求体 发送出去
/*
var from = new FormData()
form.append('name','zs')
form.append('age',20)
这种方式传 不可行
*/
//用查询参数的方式进行传 name=zs&age=20
var sendData = new URLSearchParams() //URLSearchParams是查询参数
sendData.append('name','ls')
sendData.append('age',30)
fetch ('http://39.106.32.91:3000/api/post',{
method:'POST',
body:sendData
})
.then(response=>response.json())
.then(data=>console.log(data))
注意
fetch API 无法发起JSONP请求 (跨域请求)
使用fetch-jsonp 实现跨域 (用法和fetch完全一样)
1: cnpm i fetch-jsonp -S
2:导入: import fetchJSONP from ‘fetch-jsonp’
fetchJSONP (‘跨域的地址https://api.douban.com/v2/movie/in_theaters’)
.then(response=>response.json())
.then(data=>console.log(data))
在自己的项目中使用:
inde.js
React.Component.prototype.$http = fetchJSONP //把 fetchJSONP 挂载到 每个 组件上
页面上 直接用 fetch-jsonp 结合 Promise获取数据
getMovie = ()=>{
this.$http( 'https://api.douban.com/v2/movie/in_theaters' ).then(res=>res.json())
.then(data=>console.log(data))
}
fetch-jsonp 结合 async 和await使用
getMovie = async()=>{
const res = await this.$http('https://api.douban.com/v2/movie/in_theaters')
const data = await res.json()
console.log(data)
}
import fetchJSONP from ‘fetch-jsonp’
设置自己的baseurl
React.Component.prototype.baseURL = “公共地址”
//挂载 发起JSONP请求的API
React.Component.prototype.
h
t
t
p
=
f
e
t
c
h
J
S
O
N
P
这
个
f
e
t
c
h
−
j
s
o
n
p
不
会
给
我
们
拼
接
地
址
,
所
以
用
时
这
位
样
做
t
h
i
s
.
http = fetchJSONP 这个fetch-jsonp不会给我们拼接 地址, 所以用时这位样做 this.
http=fetchJSONP这个fetch−jsonp不会给我们拼接地址,所以用时这位样做this.http(this.baseURL + ‘请求地址’)