Fetch()

Fetch()

发布于 2018-11-21   约 7 分钟

Fetch()提供了一种方式进行跨网络异步请求资源的方式,用于访问和操作HTTP管道的部分,比如:请求和相应


fetch常见的坑:
  • 接收到表示错误的HTTP状态码时,fetch()返回的Promise不会被标记为reject(即使状态码为404或500)。fetch()会将Promise状态标记为resolve(但resolve返回值但OK 属性设置为 false)。网络故障或请求被阻止才会标记为reject。
  • fetch()不会从服务端发送或接收任何cookies。发送cookies 需要设置 fetch(url, {credentials: 'include'}) 选项。

原始XHR请求

var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json'; xhr.onload = function() { console.log(xhr.response); }; xhr.onerror = function() { console.log("Oops, error"); }; xhr.send();

fetch请求

fetch(url).then(function(response) {
  return response.json(); }).then(function(data) { console.log(data); }).catch(function(e) { console.log("Oops, error"); });

使用箭头函数:

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

获取一个JSON文件,并打印到控制台。指明资源路径,然后返回一个Response对象,使用json()方法获取JSON但内容。

fetch参数

fetch()接受第二个可选参数,控制不同配置的init参数。

// Example POST method implementation:

postData('http://example.com/answer', {answer: 42}) .then(data => console.log(data)) // JSON from `response.json()` call .catch(error => console.error(error)) function postData(url, data) { // Default options are marked with * return fetch(url, { body: JSON.stringify(data), // must match 'Content-Type' header cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, same-origin, *omit headers: { 'user-agent': 'Mozilla/4.0 MDN Example', 'content-type': 'application/json' }, method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, cors, *same-origin redirect: 'follow', // manual, *follow, error referrer: 'no-referrer', // *client, no-referrer }) .then(response => response.json()) // parses response to JSON }

包含凭据的请求

包含凭据的请求:

fetch('https://example.com', {
    //将credentials: 'include'添加到传递给fetch()方法的init对象
    credentials: 'include' 
})

若在同源橱发送凭据:

fetch('https://example.com', {
  credentials: 'same-origin'  
})

确保浏览器不在请求中包含凭据:

fetch('https://example.com', {
  credentials: 'omit'  
})

上传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));

上传文件

使用 <input type="file" />FormData() 和 fetch()

Headers

使用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");

内容可被获取:

console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false

总结一下,Fetch 优点主要有:

  • 语法简洁,更加语义化
  • 基于标准 Promise 实现,支持 async/await
  • 同构方便,使用 isomorphic-fetch

猜你喜欢

转载自www.cnblogs.com/lidune/p/12576741.html