React项目搭配 fetch API 发起ajax请求

基于Promise规范的fetch API的使用

fetch的使用

  1. 注意: fetch 无法 发起JSONP 请求
  2. 作用:fetch 这个API,是专门用来发起Ajax请求的;

  3. fetch 是由原生 JS 提供的 API,专门用来取代XHR这个对象的;

    • 第一个.then 中获取到的不是最终的数据,而是一个中间的数据流对象;
    • 第一个 .then 中获取到的数据,是 一个 Response 类型的对象;
      第二个 .then 中,获取到的才是真正的 数据;
fetch('请求的url地址').then(response => res.json()).then(data= > console.log(data))
发起 Get 请求:
  1. 默认fetch('url')的话,发起的是 Get 请求
  2. 第一个 .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)
  })
  • 注意事项:
  1. 在调用 fetchJsonp的时候,小括号中写的就是 你请求的API 地址
  2. 当调用fetchJsonp 以后,得到的是一个 Promise 实例对象,需要为 这个 Promise 实例对象,通过.then指定成功的回调函数,在第一个 .then()中无法拿到最终的数据,拿到的是一个 Response 类型的对象;
  3. 在 第一个 .then中,需要return response.json()从而返回一个新的Promise 实例;
  4. 为 第一个 .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)
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落花流雨

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值