美文网首页扣丁学堂HTML5培训程序员
扣丁学堂HTML5分享h5中的fetch方法解读

扣丁学堂HTML5分享h5中的fetch方法解读

作者: 994d14631d16 | 来源:发表于2018-07-26 10:58 被阅读4次

    本篇文章扣丁学堂HTML5培训小编和大家分享一下h5中的fetch方法,对HTML5感兴趣的小伙伴就随着小编一起来了解一下吧。

    HTML5培训

    Fetch概念:

    fetch身为H5中的一个新对象,他的诞生,是为了取代ajax的存在而出现,主要目的仅仅只是为了结合ServiceWorkers,来达到以下优化:

    1. 优化离线体验

    2. 保持可扩展性

    当然如果ServiceWorkers和浏览器端的数据库IndexedDB配合,那么恭喜你,每一个浏览器都可以成为一个代理服务器一样的存在。(然而我并不认为这样是好事,这样会使得前端越来越重,走以前c/s架构的老路)

    1、前言

    既然是h5的新方法,肯定就有一些比较older的浏览器不支持了,对于那些不支持此方法的

    浏览器就需要额外的添加一个polyfill:

    2、用法

    ferch(抓取) :

    HTML:

    fetch('/users.html') //这里返回的是一个Promise对象,不支持的浏览器需要相应的ployfill或通过babel等转码器转码后在执行

        .then(function(response) {

        return response.text()})

        .then(function(body) {

        document.body.innerHTML = body

    })

    JSON :

    fetch('/users.json')

        .then(function(response) {

        return response.json()})

        .then(function(json) {

        console.log('parsed json', json)})

        .catch(function(ex) {

        console.log('parsing failed', ex)

    })

    Response metadata :

    fetch('/users.json').then(function(response) {

      console.log(response.headers.get('Content-Type'))

      console.log(response.headers.get('Date'))

      console.log(response.status)

      console.log(response.statusText)

    })

    Post form:

    var form = document.querySelector('form')

    fetch('/users', {

      method: 'POST',

      body: new FormData(form)

    })

    Post JSON:

    fetch('/users', {

      method: 'POST',

      headers: {

        'Accept': 'application/json',

        'Content-Type': 'application/json'

      },

      body: JSON.stringify({  //这里是post请求的请求体

        name: 'Hubot',

        login: 'hubot',

      })

    })

    File upload:

    var input = document.querySelector('input[type="file"]')

    var data = new FormData()

    data.append('file', input.files[0]) //这里获取选择的文件内容

    data.append('user', 'hubot')

    fetch('/avatars', {

      method: 'POST',

      body: data

    })

    3、注意事项

    (1)和ajax的不同点:

    1. fatch方法抓取数据时不会抛出错误即使是404或500错误,除非是网络错误或者请求过程中被打断.但当然有解决方法啦,下面是demonstration:

    function checkStatus(response) {

      if (response.status >= 200 && response.status < 300) { //判断响应的状态码是否正常

        return response //正常返回原响应对象

      } else {

        var error = new Error(response.statusText) //不正常则抛出一个响应错误状态信息

        error.response = response

        throw error

      }

    }

    function parseJSON(response) {

      return response.json()

    }

    fetch('/users')

      .then(checkStatus)

      .then(parseJSON)

      .then(function(data) {

        console.log('request succeeded with JSON response', data)

      }).catch(function(error) {

        console.log('request failed', error)

      })

    2.一个很关键的问题,fetch方法不会发送cookie,这对于需要保持客户端和服务器端常连接就很致命了,因为服务器端需要通过cookie来识别某一个session来达到保持会话状态.要想发送cookie需要修改一下信息:

    fetch('/users', {

      credentials: 'same-origin'  //同域下发送cookie

    })

    fetch('https://segmentfault.com', {

      credentials: 'include'     //跨域下发送cookie

    })

    以上就是扣丁学堂HTML5在线学习给大家分享的h5中的fetch方法解读,希望对小伙伴所有帮助。想要了解更多内容的小伙伴可以登录扣丁学堂官网咨询。扣丁学堂是专业的HTML5培训班,不仅有专业的老师和与时俱进的课程体系,还有大量的HTML5视频教程供学员观看学习哦。

    相关文章

      网友评论

        本文标题:扣丁学堂HTML5分享h5中的fetch方法解读

        本文链接:https://www.haomeiwen.com/subject/irnvmftx.html