fetch用法说明
语法说明
fetch(url, options).then(function(response) {
// handle HTTP response
}, function(error) {
// handle network error
})
具体参数案例:
//兼容包
require('babel-polyfill')
require('es6-promise').polyfill()
import 'whatwg-fetch'
fetch(url, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
},
credentials: "same-origin"
}).then(function(response) {
response.status //=> number 100–599
response.statusText //=> String
response.headers //=> Headers
response.url //=> String
response.text().then(function(responseText) { ... })
}, function(error) {
error.message //=> String
})
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。
response
一个 Promise,resolve 时回传 Response 对象:
属性:
status (number)- HTTP请求结果参数,在100–599 范围statusText (String)- 服务器返回的状态报告ok (boolean)- 如果返回200表示请求成功则为trueheaders (Headers)- 返回头部信息,下面详细介绍url (String)- 请求的地址
方法:
text()- 以string的形式生成请求textjson()- 生成JSON.parse(responseText)的结果blob()- 生成一个BlobarrayBuffer()- 生成一个ArrayBufferformData()- 生成格式化的数据,可用于其他的请求
其他方法:
clone()Response.error()Response.redirect()
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的信息
使用案例
GET请求
HTML
fetch('/users.html')
.then(function(response) {
return response.text()
}).then(function(body) {
document.body.innerHTML = body
})IMAGE
var myImage = document.querySelector('img'); fetch('flowers.jpg')
.then(function(response) {
return response.blob();
})
.then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});JSON
fetch(url)
.then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(e) {
console.log("Oops, error");
});
使用 ES6 的 箭头函数 后:
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))
response的数据
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请求
fetch('/users', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
})
检查请求状态
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)
})
采用promise形式
Promise 对象是一个返回值的代理,这个返回值在promise对象创建时未必已知。它允许你为异步操作的成功或失败指定处理方法。 这使得异步方法可以像同步方法那样返回值:异步方法会返回一个包含了原返回值的 promise 对象来替代原返回值。
Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve方法和reject方法。如果异步操作成功,则用resolve方法将Promise对象的状态变为“成功”(即从pending变为resolved);如果异步操作失败,则用reject方法将状态变为“失败”(即从pending变为rejected)。
promise实例生成以后,可以用then方法分别指定resolve方法和reject方法的回调函数。
//创建一个promise对象
var promise = new Promise(function(resolve, reject) {
if (/* 异步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
//then方法可以接受两个回调函数作为参数。
//第一个回调函数是Promise对象的状态变为Resolved时调用,第二个回调函数是Promise对象的状态变为Reject时调用。
//其中,第二个函数是可选的,不一定要提供。这两个函数都接受Promise对象传出的值作为参数。
promise.then(function(value) {
// success
}, function(value) {
// failure
});
那么结合promise后fetch的用法:
//Fetch.js
export function Fetch(url, options) {
options.body = JSON.stringify(options.body)
const defer = new Promise((resolve, reject) => {
fetch(url, options)
.then(response => {
return response.json()
})
.then(data => {
if (data.code === 0) {
resolve(data) //返回成功数据
} else {
if (data.code === 401) {
//失败后的一种状态
} else {
//失败的另一种状态
}
reject(data) //返回失败数据
}
})
.catch(error => {
//捕获异常
console.log(error.msg)
reject()
})
})
return defer
}
调用Fech方法:
import { Fetch } from './Fetch'
Fetch(getAPI('search'), {
method: 'POST',
options
})
.then(data => {
console.log(data)
})
支持状况及解决方案
原生支持率并不高,幸运的是,引入下面这些 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
fetch用法说明的更多相关文章
- 第五节: 前后端交互之Promise用法和Fetch用法
一. Promise相关 1.说明 主要解决异步深层嵌套的问题,promise 提供了简洁的API 使得异步操作更加容易 . 2.入门使用 我们使用new来构建一个Promise Promise的构造 ...
- fetch用法
fetch(REQUEST_URL) .then((response) => response.json()) .then((responseData)=> { console.log(r ...
- 你不需要jQuery(三):新AJAX方法fetch()
XMLHttpRequest来完成ajax有些老而过时了. fetch()能让我们完成类似 XMLHttpRequest (XHR) 提供的ajax功能.它们之间的主要区别是,Fetch API 使用 ...
- Git fetch & pull
转:https://blog.csdn.net/qq_36113598/article/details/78906882 1.简单概括 先用一张图来理一下git fetch和git pull的概念: ...
- git fetch & pull详解
1.简单概括 先用一张图来理一下git fetch和git pull的概念: 可以简单的概括为: git fetch是将远程主机的最新内容拉到本地,用户在检查了以后决定是否合并到工作本机分支中. 而g ...
- 三种获取数据的方法fetch和ajax和axios
一 .fetch用法 ( 本人比较喜欢fetch,代码精简,虽说目前axios比较流行,但是fetch很多大厂已经开始用fetch开始封装了, 我觉得以后fetch会取代axios和ajax ) 1. ...
- jquery属性的相关js实现方法
有些公司手机网站开发不用第三方的jquery或者zeptio,直接用原生的javascript.原生javascript功能是蛮强大的,只不过部分属性不支持IE8以下浏览器.下面对jquery相关方法 ...
- 给所有开发者的React Native详细入门指南
建议先下载好资料后,再阅读本文.demo代码和资料下载 目录 一.前言 二.回答一些问题 1.为什么写此教程 2.本文适合哪些人看 3.如何使用本教程 4.需要先学习JavaScript.HTML.C ...
- 基于.net core 3 和 Orleans 3 的 开发框架:Phenix Framework 7
Phenix Framework 7 for .net core 3 + Orleans 3 发布地址:https://github.com/phenixiii/Phenix.NET7 2019052 ...
随机推荐
- ios各个型号设备屏幕分辨率总结
https://blog.csdn.net/amyloverice/article/details/79389357 iPhone: iPhone 1G 320x480 iPhone 3G 3 ...
- jsp页面将日期类型的数据转换成xxxx年xx月xx日xx时xx分
<fmt:formatDate value="${bsjz.cxkssj}" pattern="yyyy"/><span class=&quo ...
- kvm磁盘io优化以及性能测试以及与物理机对比
ubuntu下kvm的磁盘io性能优化步骤 1.virsh shutdown wcltest2 2.virsh edit wcltest2 <driver name='qemu' type='q ...
- C# Task任务详解及其使用方式
https://blog.csdn.net/younghaiqing/article/details/81455410 C#多线程编程笔记(4.3)-Task任务中实现取消选项 https://blo ...
- Storm概念学习系列之Storm与Hadoop的角色和组件比较
不多说,直接上干货! Storm与Hadoop的角色和组件比较 Storm 集群和 Hadoop 集群表面上看很类似.但是 Hadoop 上运行的是 MapReduce 作业,而在 Storm 上运行 ...
- JavaFX常用汇总
1. 描述备注 1.1 参考教程 博客 易百教程 JavaFX中国 1.5 安装 a). 在线安装e(fx)clipse插件 b). 下载安装SceneBuilder c). eclipse重启以后, ...
- mysql数据库的数据变更事件获取以及相关数据
https://medium.com/@Masutangu/udf-trigger%E5%AE%9E%E6%97%B6%E7%9B%91%E6%8E%A7mysql%E6%95%B0%E6%8D%AE ...
- springboot 学习笔记(九)
springboot整合activemq,实现broker集群部署(cluster) 1.为实现jms高并发操作,需要对activemq进行集群部署,broker cluster就是activemq自 ...
- spring transaction 初识
spring 事务初识 1.spring事务的主要接口,首先盗图一张,展示出spring 事务的相关接口.Spring并不直接管理事务,而是提供了多种事务管理器,他们将事务管理的职责委托给Hibern ...
- 如何从MYSQL官方YUM仓库安装MYSQL5.x 原理一样只要获取对的仓库依赖安装对的仓库依赖就ok了,我就是用这种安装的5.7
如何从MYSQL官方YUM仓库安装MYSQL5.6 2013年10月,MySQL开发团队正式宣布支持Yum仓库,这就意味着我们现在可以从这个Yum库中获得最新和最优版的MySQL安装包.本文将在一台全 ...