Fetch(个人学习笔记)

简介

  • Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。它还提供了一个全局 fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。
  • MDN地址

内容

Promise fetch(input[, init]);

  • 返回值:一个 Promise,resolve 时回传 Response 对象。
  • input 定义要获取的资源
  • init 可选 一个配置项对象,包括所有对请求的设置
  • 参数见Fetch()

基础实现

// url data为参数 data为对象
fetch(url, {
	// 请求体 
    // 注意 GET 或 HEAD 方法的请求不能包含 body 信息。
    body: JSON.stringify(data), 
    // 请求的 cache 模式
    // default、 no-store、 reload 、 no-cache 、 force-cache 或者 only-if-cached
    cache: 'no-cache', 
    // 请求的 credentials 凭据, omit、same-origin 或者 include 
    // 为了在当前域名内自动发送 cookie , 必须提供这个选项
    credentials: 'same-origin', 
    // 请求的模式,如 cors、 no-cors 或者 same-origin。
    // 同源策略
    headers: {
      'user-agent': 'Mozilla/4.0 MDN Example',
      'content-type': 'application/json'
    }, // 请求的头信息
    method: 'POST', // 请求方法 GET, POST, PUT, DELETE, etc.
    // 请求的模式,如 cors、 no-cors 或者 same-origin。
    mode: 'cors', 
    // 可用的 redirect 模式
    // follow (自动重定向), error (如果产生重定向将自动终止并且抛出一个错误), 或者 manual (手动处理重定向). 
    //在Chrome中默认使用follow(Chrome 47之前的默认值是manual)。
    redirect: 'follow', 
    //  一个 USVString 可以是 no-referrer、client或一个 URL。默认是 client。
    referrer: 'no-referrer',
    // referrerPolicy: 指定了HTTP头部referer字段的值。
    // 可能为以下值之一: no-referrer、 no-referrer-when-downgrade、 origin、 origin-when-cross-origin、 unsafe-url 。
    // integrity 包括请求的  subresource integrity 值 ( 例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。
  })
  .then(response => response.json()) // parses response to JSON

发送带凭据的请求

fetch('https://example.com', {
  // include 包含凭据 可跨域
  // same-origin 只能同源 包含凭据
  // omit 不包含凭据
  credentials: 'include'
})

上传JSON数据

var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers: new Headers({
    'Content-Type': 'application/json'
  })
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

上传文件

  • 可以通过 HTML 元素,FormData() 和 fetch() 上传文件。
var formData = new FormData();
var fileField = document.querySelector("input[type='file']");

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

上传多个文件

  • 可以通过HTML 元素,FormData() 和 fetch() 上传文件。
var formData = new FormData();
var photos = document.querySelector("input[type='file'][multiple]");

formData.append('title', 'My Vegas Vacation');
// formData 只接受文件、Blob 或字符串,不能直接传递数组,所以必须循环嵌入
for (let i = 0; i < photos.files.length; i++) {
    formData.append('photo', photos.files[i]);
}

fetch('https://example.com/posts', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

检测请求是否成功

  • 想要精确的判断 fetch() 是否成功,需要包含 promise resolved 的情况,此时再判断 Response.ok 是不是为 true。类似以下代码:
fetch('flowers.jpg').then(function(response) {
  if(response.ok) {
    return response.blob();
  }
  throw new Error('Network response was not ok.');
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
}).catch(function(error) {
  console.log('There has been a problem with your fetch operation: ', error.message);
});

自定义请求对象

  • 除了传给 fetch() 一个资源的地址,你还可以通过使用 Request() 构造函数来创建一个 request 对象,然后再作为参数传给 fetch()
var myHeaders = new Headers();

var myInit = { method: 'GET',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default' };

var myRequest = new Request('flowers.jpg', myInit);

fetch(myRequest).then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

Headers对象

  • var myHeaders = new Headers(init);
    • init 可选 通过一个包含任意 HTTP headers 的对象来预设你的 Headers
// 设置Headers对象
var content = "Hello World";
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
// or
myHeaders = new Headers({
  "Content-Type": "text/plain",
  "Content-Length": content.length.toString(),
  "X-Custom-Header": "ProcessThisImmediately",
});
// 获取Headers对象属性
console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false
myHeaders.set("Content-Type", "text/html");
myHeaders.append("X-Custom-Header", "AnotherValue");

console.log(myHeaders.get("Content-Length")); // 11
console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]

myHeaders.delete("X-Custom-Header");
console.log(myHeaders.getAll("X-Custom-Header")); // [ ]

Guard属性

  • Headers 对象有一个特殊的 guard 属性。这个属性没有暴露给 Web,但是它影响到哪些内容可以在 Headers 对象中被操作。
  • none:默认的
  • request:从 request 中获得的 headers(Request.headers)只读
  • request-no-cors:从不同域(Request.mode no-cors)的 request 中获得的 headers 只读
  • response:从 response 中获得的 headers(Response.headers)只读
  • immutable:在 ServiceWorkers 中最常用的,所有的 headers 都只读。

Response对象

  • Response 实例是在 fetch() 处理完 promise 之后返回的。

会用到的最常见的 response 属性有:

* Response.status — 整数(默认值为200)为response的状态码。
* Response.statusText — 字符串(默认值为"OK"),该值与 HTTP 状态码消息对应。
* Response.ok — 如上所示,该属性是来检查response的状态是否在 200 - 299(包括200 和 299)这个范围内。该属性返回一个布尔值 (en-US)。

方法

  • Response.blob()
    • Response mixin的 blob()方法使用一个 Response 流,并将其读取完成。它返回一个使用Blob解决的promise。
response.blob().then(function(myBlob) {
  // do something with myBlob
});
var myImage = document.querySelector('img');

var myRequest = new Request('flowers.jpg');

fetch(myRequest)
.then(function(response) {
  return response.blob();
})
.then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});
  • Response.json()
    • Response mixin 的 json() 方法接收一个 Response 流,并将其读取完成。它返回一个 Promise,Promise 的解析 resolve 结果是将文本体解析为 JSON。
response.json().then(data => {
  // do something with your data
});
  • Response.text()
    • Response mixin 的 text() 方法提供了一个可供读取的“返回流”(Response stream),并将它读取完。它返回一个包含 USVString 对象(也就是文本)的 Promise 对象,返回结果的编码永远是 UTF-8。
response.text().then(function (text) {
  // do something with the text response
});
  • Response.formData()
    • Response 对象中的formData() 方法将 Response 对象中的所承载的数据流读取并封装成为一个对象,该方法将返回一个 Promise 对象,该对象将产生一个FormData 对象。
    • 该方法主要与 service workers 有关.
response.formData()
.then(function(formdata) {
  // do something with your formdata
});

Body

  • 请求体
  1. 类型:
    • ArrayBuffer
    • ArrayBufferView (Uint8Array等)
    • Blob/File
    • string
    • URLSearchParams
    • FormData

特性检测

if(self.fetch) {
    // run my fetch request here
} else {
    // do something with XMLHttpRequest?
}

注意

  1. 成功的 fetch() 检查不仅要包括 promise 被 resolve,还要包括 Response.ok 属性为 true。HTTP 404 状态并不被认为是网络错误。
  2. 从Firefox 43开始,如果fetch()接收到含有用户名和密码的URL(例如http://user:password@example.com),它将会抛出一个TypeError 。
  3. fetch() 可以接受跨域 cookies;你也可以使用 fetch() 建立起跨域会话。
  4. fetch 不会发送 cookies。除非你使用了credentials 的初始化选项。(自 2017 年 8 月 25 日以后,默认的 credentials 政策变更为 same-origin。Firefox 也在 61.0b13 版本中进行了修改)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值