经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
fetch()函数说明与使用方法详解
来源:jb51  时间:2022/11/28 8:56:06  对本文有异议

Fetch() 是 window.fetch 的 JavaScript polyfill。

全局 fetch() 函数是 web 请求和处理响应的简单方式,不使用 XMLHttpRequest。这个 polyfill 编写的接近标准的 Fetch 规范。

fetch()是XMLHttpRequest的升级版,用于在JavaScript脚本里面发出 HTTP 请求。

fetch()的功能与 XMLHttpRequest 基本相同,但有三个主要的差异。

(1)fetch()使用 Promise,不使用回调函数,因此大大简化了写法,写起来更简洁。

(2)采用模块化设计,API 分散在多个对象上(Response 对象、Request 对象、Headers 对象),更合理一些;相比之下,XMLHttpRequest 的 API 设计并不是很好,输入、输出、状态都在同一个接口管理,容易写出非常混乱的代码

(3)fetch()通过数据流(Stream 对象)处理数据,可以分块读取,有利于提高网站性能表现,减少内存占用,对于请求大文件或者网速慢的场景相当有用。XMLHTTPRequest 对象不支持数据流,

所有的数据必须放在缓存里,不支持分块读取,必须等待全部拿到后,再一次性吐出来。在用法上接受一个 URL 字符串作为参数,默认向该网址发出 GET 请求,返回一个 Promise 对象

fetch()函数支持所有的 HTTP 方式:

获取HTML类型数据

  1. fetch('/users.html')
  2. ??.then(function(response)?{
  3. ????return?response.text()
  4. ??}).then(function(body)?{
  5. ????document.body.innerHTML?=?body
  6. ??})

获取JSON类型数据

  1. fetch('/users.json')
  2. ??.then(function(response)?{
  3. ????return?response.json()
  4. ??}).then(function(json)?{
  5. ????console.log('parsed?json',?json)
  6. ??}).catch(function(ex)?{
  7. ????console.log('parsing?failed',?ex)
  8. ??})

一:fetch()语法说明

  1. fetch(url, options).then(function(response) {
  2. // handle HTTP response
  3. }, function(error) {
  4. // handle network error
  5. })

具体参数案例:

  1. require('babel-polyfill')
  2. require('es6-promise').polyfill()
  3. import 'whatwg-fetch'
  4. fetch(url, {
  5. method: "POST",
  6. body: JSON.stringify(data),
  7. headers: {
  8. "Content-Type": "application/json"
  9. },
  10. credentials: "same-origin"
  11. }).then(function(response) {
  12. response.status //=> number 100–599
  13. response.statusText //=> String
  14. response.headers //=> Headers
  15. response.url //=> String
  16. response.text().then(function(responseText) { ... })
  17. }, function(error) {
  18. error.message //=> String
  19. })

1.url定义要获取的资源。

这可能是:
• 一个 USVString 字符串,包含要获取资源的 URL。
• 一个 Request 对象。
options(可选)
一个配置项对象,包括所有对请求的设置。可选的参数有:
• method: 请求使用的方法,如 GET、POST。
• headers: 请求的头信息,形式为 Headers 对象或 ByteString。
• body: 请求的 body 信息:可能是一个 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息。
• mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
• credentials: 请求的 credentials,如 omit、same-origin 或者 include。
• cache: 请求的 cache 模式: default, no-store, reload, no-cache, force-cache, 或者 only-if-cached。
 

2.response一个 Promise,resolve 时回传 Response 对象:

• 属性:
o status (number) - HTTP请求结果参数,在100–599 范围
o statusText (String) - 服务器返回的状态报告
o ok (boolean) - 如果返回200表示请求成功则为true
o headers (Headers) - 返回头部信息,下面详细介绍
o url (String) - 请求的地址
• 方法:
o text() - 以string的形式生成请求text
o json() - 生成JSON.parse(responseText)的结果
o blob() - 生成一个Blob
o arrayBuffer() - 生成一个ArrayBuffer
o formData() - 生成格式化的数据,可用于其他的请求
• 其他方法:
o clone()
o Response.error()
o Response.redirect()
 

3.response.headers

• has(name) (boolean) - 判断是否存在该信息头
• get(name) (String) - 获取信息头的数据
• getAll(name) (Array) - 获取所有头部数据
• set(name, value) - 设置信息头的参数
• append(name, value) - 添加header的内容
• delete(name) - 删除header的信息
• forEach(function(value, name){ ... }, [thisContext]) - 循环读取header的信息

二:具体使用案例

1.GET请求

• HTML数据:

  1. fetch('/users.html')
  2. .then(function(response) {
  3. return response.text()
  4. }).then(function(body) {
  5. document.body.innerHTML = body
  6. })

• IMAGE数据

  1. var myImage = document.querySelector('img');
  2. fetch('flowers.jpg')
  3. .then(function(response) {
  4. return response.blob();
  5. })
  6. .then(function(myBlob) {
  7. var objectURL = URL.createObjectURL(myBlob);
  8. myImage.src = objectURL;
  9. });

• JSON数据

  1. fetch(url)
  2. .then(function(response) {
  3. return response.json();
  4. }).then(function(data) {
  5. console.log(data);
  6. }).catch(function(e) {
  7. console.log("Oops, error");
  8. });

使用 ES6 的 箭头函数后:

  1. fetch(url)
  2. .then(response => response.json())
  3. .then(data => console.log(data))
  4. .catch(e => console.log("Oops, error", e))

response的数据

  1. fetch('/users.json').then(function(response) {
  2. console.log(response.headers.get('Content-Type'))
  3. console.log(response.headers.get('Date'))
  4. console.log(response.status)
  5. console.log(response.statusText)
  6. })

POST请求

  1. fetch('/users', {
  2. method: 'POST',
  3. headers: {
  4. 'Accept': 'application/json',
  5. 'Content-Type': 'application/json'
  6. },
  7. body: JSON.stringify({
  8. name: 'Hubot',
  9. login: 'hubot',
  10. })
  11. })

检查请求状态

  1. function checkStatus(response) {
  2. if (response.status >= 200 && response.status < 300) {
  3. return response
  4. } else {
  5. var error = new Error(response.statusText)
  6. error.response = response
  7. throw error
  8. }
  9. }
  10. function parseJSON(response) {
  11. return response.json()
  12. }
  13. fetch('/users')
  14. .then(checkStatus)
  15. .then(parseJSON)
  16. .then(function(data) {
  17. console.log('request succeeded with JSON response', data)
  18. }).catch(function(error) {
  19. console.log('request failed', error)
  20. })

采用promise形式

Promise 对象是一个返回值的代理,这个返回值在promise对象创建时未必已知。它允许你为异步操作的成功或失败指定处理方法。 这使得异步方法可以像同步方法那样返回值:异步方法会返回一个包含了原返回值的 promise 对象来替代原返回值。
Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve方法和reject方法。如果异步操作成功,则用resolve方法将Promise对象的状态变为“成功”(即从pending变为resolved);如果异步操作失败,则用reject方法将状态变为“失败”(即从pending变为rejected)。
promise实例生成以后,可以用then方法分别指定resolve方法和reject方法的回调函数。

  1. //创建一个promise对象
  2. var promise = new Promise(function(resolve, reject) {
  3. if (/* 异步操作成功 */){
  4. resolve(value);
  5. } else {
  6. reject(error);
  7. }
  8. });
  9. //then方法可以接受两个回调函数作为参数。
  10. //第一个回调函数是Promise对象的状态变为Resolved时调用,第二个回调函数是Promise对象的状态变为Reject时调用。
  11. //其中,第二个函数是可选的,不一定要提供。这两个函数都接受Promise对象传出的值作为参数。
  12. promise.then(function(value) {
  13. // success
  14. }, function(value) {
  15. // failure
  16. });

那么结合promise后fetch的用法:

  1. //Fetch.js
  2. export function Fetch(url, options) {
  3. options.body = JSON.stringify(options.body)
  4. const defer = new Promise((resolve, reject) => {
  5. fetch(url, options)
  6. .then(response => {
  7. return response.json()
  8. })
  9. .then(data => {
  10. if (data.code === 0) {
  11. resolve(data) //返回成功数据
  12. } else {
  13. if (data.code === 401) {
  14. //失败后的一种状态
  15. } else {
  16. //失败的另一种状态
  17. }
  18. reject(data) //返回失败数据
  19. }
  20. })
  21. .catch(error => {
  22. //捕获异常
  23. console.log(error.msg)
  24. reject()
  25. })
  26. })
  27. return defer
  28. }

调用Fech方法:

  1. import { Fetch } from './Fetch'
  2. Fetch(getAPI('search'), {
  3. method: 'POST',
  4. options
  5. })
  6. .then(data => {
  7. console.log(data)
  8. })

三:支持状况及解决方案

原生支持率并不高,幸运的是,引入下面这些 polyfill 后可以完美支持 IE8+ :

• 由于 IE8 是 ES3,需要引入 ES5 的 polyfill: es5-shim, es5-sham
• 引入 Promise 的 polyfill: es6-promise
• 引入 fetch 探测库:fetch-detector
• 引入 fetch 的 polyfill: fetch-ie8
• 可选:如果你还使用了 jsonp,引入 fetch-jsonp
• 可选:开启 Babel 的 runtime 模式,现在就使用 async/await

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号