基于Promise规范的fetch API
的使用
fetch的使用
注意: fetch 无法 发起
JSONP 请求
作用:fetch 这个
API
,是专门用来发起Ajax请求的;fetch 是由原生
JS
提供的API
,专门用来取代XHR
这个对象的;
- 第一个.then 中获取到的不是最终的数据,而是一个中间的数据流对象;
- 第一个 .then 中获取到的数据,是 一个 Response 类型的对象;
第二个 .then 中,获取到的才是真正的 数据;fetch('请求的url地址').then(response => res.json()).then(data= > console.log(data))
发起 Get 请求:
- 默认
fetch('url')
的话,发起的是 Get 请求- 第一个
.then
中这个 response 就是 服务器返回的可读数据流,内部存储的是二进制数据;
.json()
的作用,就是读取 response 这个二进制数据流,并把 读取到的数据,转为
JSON
格式的 Promise对象第二个
.then
中 拿到的 data,就是最终的数据fetch('http://39.106.32.91:3000/api/getlunbo') .then(response => { return response.json() }) .then(data => { console.log(data) })
发起 Post 请求:
使用
new URLSearchParams()
// 这是 查询参数 name=zs&age=20 var sendData = new 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-jsonp的使用
fetch-jsonp
最基本的用法:运行
cnpm i fetch-jsonp -S
在项目的
index.js
文件中,导入import fetchJsonp from 'fetch-jsonp' {/* 把 fetch-jsonp 挂载到每个组件上*/} React.Component.prototype.$http = fetchJsonp
总结: 第一个.then拿到的是中间数据; 第二个.then中拿到的才是最终的数据;
response.json()
当我们为 response 对象调用了它的.json()
方法以后,返回的是新的 promise 实例对象
fetchJsonp('https://api.douban.com/v2/movie/in_theaters') .then( res => res.json()) .then( (result) => { console.log(result) })
- 注意事项:
- 在调用
fetchJsonp
的时候,小括号中写的就是 你请求的API 地址
- 当调用
fetchJsonp
以后,得到的是一个 Promise 实例对象,需要为 这个 Promise 实例对象,通过.then
指定成功的回调函数,在第一个.then()
中无法拿到最终的数据,拿到的是一个Response
类型的对象;- 在 第一个
.then
中,需要return response.json()
从而返回一个新的Promise 实例;- 为 第一个
.then()
中返回的promise实例,再次通过.then指定成功回调,拿到的才是最终的数据;
fetch-jsonp结合async和await一起使用
运行
cnpm i fetch-jsonp -S
在项目的
index.js
文件中,导入import fetchJsonp from 'fetch-jsonp' {/* 把 fetch-jsonp 挂载到每个组件上*/} React.Component.prototype.$http = fetchJsonp // 请求根路径 React.Component.prototype.baseURL = 'https://api.douban.com/v2'
getList = async ()=>{
const res = await this.$http('https://api.douban.com/v2/movie/in_theaters')
const data = await res.json()
console.log(data)
}