基于Promise规范的fetch API的使用

基于Promise规范的fetch API的使用

fetch的使用

  1. 作用:fetch 这个API,是专门用来发起Ajax请求的;

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

    fetch('请求的url地址').then(response => res.json()).then(data= > console.log(data))
    // 注意: 第一个.then 中获取到的不是最终的数据,而是一个中间的数据流对象;
    // 注意: 第一个 .then 中获取到的数据,是 一个 Response 类型的对象;
    // 第二个 .then 中,获取到的才是真正的 数据;
  3. 发起 Get 请求:

    // 默认 fetch('url') 的话,发起的是 Get 请求
      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)
        })

  4. 发起 Post 请求:

    // 这是 查询参数   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))
  5. 注意: fetch 无法 发起 JSONP 请求

fetch-jsonp的使用

  1. fetch-jsonp最基本的用法:

    fetchJsonp('https://api.douban.com/v2/movie/in_theaters')
      .then(function (response) {
        // response.json()   当我们为 response 对象调用了它的 .json() 方法以后,返回的是新的 promise 实例对象
        return response.json()
      })
      .then(function (result) {
        console.log(result)
      })
  2. 注意事项:

    1. 在调用 fetchJsonp 的时候,小括号中写的就是 你请求的 API 地址
    2. 当调用 fetchJsonp 以后,得到的是一个 Promise 实例对象,需要为 这个 Promise 实例对象,通过.then指定成功的回调函数,在第一个 .then()中无法拿到最终的数据,拿到的是一个 Response 类型的对象;
    3. 在 第一个 .then中,需要return response.json()从而返回一个新的Promise 实例;
    4. 为 第一个 .then()中返回的promise实例,再次通过.then指定成功回调,拿到的才是最终的数据;

    总结: 第一个.then拿到的是中间数据; 第二个.then中拿到的才是最终的数据;

猜你喜欢

转载自www.cnblogs.com/var-chu/p/9648766.html