作用:fetch 这个API,是专门用来发起Ajax请求的;
fetch 是由原生 JS 提供的 API ,专门用来取代 XHR 这个对象的;
fetch(‘请求的url地址‘).then(response => res.json()).then(data= > console.log(data))
// 注意: 第一个.then 中获取到的不是最终的数据,而是一个中间的数据流对象;
// 注意: 第一个 .then 中获取到的数据,是 一个 Response 类型的对象;
// 第二个 .then 中,获取到的才是真正的 数据;发起 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)
    })?
发起 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))注意: fetch 无法 发起 JSONP 请求
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)
  })注意事项:
.then指定成功的回调函数,在第一个 .then()中无法拿到最终的数据,拿到的是一个 Response 类型的对象;.then中,需要return response.json()从而返回一个新的Promise 实例;.then()中返回的promise实例,再次通过.then指定成功回调,拿到的才是最终的数据;总结: 第一个.then拿到的是中间数据; 第二个.then中拿到的才是最终的数据;
原文:https://www.cnblogs.com/var-chu/p/9648766.html