Using Fetch
【Using Fetch】
This kind of functionality was previously achieved using XMLHttpRequest
. Fetch provides a better alternative that can be easily used.
需要注意以下2点:
1)The Promise returned from fetch()
won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok
status set to false), and it will only reject on network failure or if anything prevented the request from completing.
2)By default, fetch
won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).
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;
});
下面的示例,控制了HTTP Header
var myHeaders = new Headers(); var myInit = { method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default' }; fetch('flowers.jpg', myInit).then(function(response) {
return response.blob();
}).then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
【credentials
】
fetch('https://example.com', {
credentials: 'include'
})
// The calling script is on the origin 'https://example.com' fetch('https://example.com', {
credentials: 'same-origin'
})
fetch('https://example.com', {
credentials: 'omit'
})
【错误处理】
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);
});
【Request对象】
Request()
accepts exactly the same parameters as the fetch()
method. You can even pass in an existing request object to create a copy of it:
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】
All of the Headers methods throw a TypeError
if a header name is used that is not a valid HTTP Header name.
A good use case for headers is checking whether the content type is correct before you process it further.
fetch(myRequest).then(function(response) {
var contentType = response.headers.get("content-type");
if(contentType && contentType.includes("application/json")) {
return response.json();
}
throw new TypeError("Oops, we haven't got JSON!");
})
.then(function(json) { /* process your JSON further */ })
.catch(function(error) { console.log(error); });
【Response】
Response.status
— An integer (default value 200) containing the response status code.Response.statusText
— A string (default value "OK"),which corresponds to the HTTP status code message.Response.ok
— seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns aBoolean
.
参考:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Using Fetch的更多相关文章
- Git 少用 Pull 多用 Fetch 和 Merge
本文有点长而且有点乱,但就像Mark Twain Blaise Pascal的笑话里说的那样:我没有时间让它更短些.在Git的邮件列表里有很多关于本文的讨论,我会尽量把其中相关的观点列在下面. 我最常 ...
- git提示:Fatal:could not fetch refs from ....
在git服务器上新建项目提示: Fatal:could not fetch refs from git..... 百度搜索毫无头绪,最后FQgoogle,找到这篇文章http://www.voidcn ...
- sublime 插件推荐: Nettuts+ Fetch
Nettuts+ Fetch github地址:Nettuts-Fetch 在sublime中直接用 ctrl+shift+P -> pci -> Nettuts-Fetch 即可下载 这 ...
- git pull和git fetch的区别
Git中从远程的分支获取最新的版本到本地有这样2个命令:1. git fetch:相当于是从远程获取最新版本到本地,不会自动merge Git fetch origin master git log ...
- Hibernate之加载策略(延迟加载与即时加载)和抓取策略(fetch)
假设现在有Book和Category两张表,表的关系为双向的一对多,表结构如下: 假设现在我想查询id为2的那本书的书名,使用session.get(...)方法: Session session=H ...
- SQL Server 2012提供的OFFSET/FETCH NEXT与Row_Number()对比测试(转)
原文地址:http://www.cnblogs.com/downmoon/archive/2012/04/19/2456451.html 在<SQL Server 2012服务端使用OFFSET ...
- Attempt to fetch logical page (...) in database 2 failed. It belongs to allocation unit xxxx not to xxx
今天一个同事说在一个生产库执行某个存储过程,遇到了错误: Fatal error 605 occurred at jul 29 2014 我试着执行该存储过程,结果出现下面错误,每次执行该存储过程,得 ...
- Fetch:下一代 Ajax 技术
Ajax,2005年诞生的技术,至今已持续了 10 年.它是一种在客户端创建一个异步请求的技术,本质上它不算创新,是一组技术的组合.它的核心对象是 XMLHttpRequest. 简单回顾下历史 19 ...
- 在 JS 中使用 fetch 更加高效地进行网络请求
在前端快速发展地过程中,为了契合更好的设计模式,产生了 fetch 框架,此文将简要介绍下 fetch 的基本使用. 我的源博客地址:http://blog.parryqiu.com/2016/03/ ...
- 解决:error: Cannot fetch repo (TypeError: expected string or buffer)
同步源码,问题重现: Fetching project platform/external/libopus Fetching project repo error: Cannot fetch repo ...
随机推荐
- 剑指offer(一):二维数组中的查找
说明: 1.本系列是根据<剑指Offer>这个系列做的一个小笔记. 2.直接动力是因为师兄师姐找工作很难,而且机械出生的我面试算法更难. 3.刚开始准备刷LeetCode.LintCode ...
- spring初始化相关
获取applicationContext implements ApplicationContextAware @Override public void setApplicationContext( ...
- [转]ORA-12560: TNS: 协议适配器错误
转自:http://worms.blog.51cto.com/969144/1293265 Sqlplus 登陆oracle时报错ORA-12560:TNS: 协议适配器错误 如下:C:\Users\ ...
- 【HQL】常用函数
CONCAT_WS(separator, str1, str2,...) 多列转1列,以分割符分割 使用场景: 1.多列在一列显示: 2.多列转多行作为辅助,结合split和explode使用 SEL ...
- windows清除访问共享文件夹的登陆信息
https://jingyan.baidu.com/article/c843ea0b70797e77931e4a96.html 当在命令提示窗口输入net use命令时,会显示本机缓存的共享登录信息, ...
- java 常用第3方工具
https://www.cnblogs.com/chenpi/p/5608628.html#_label4
- pycharm 直接删掉数据表之后,makemigration和migrate 之后,数据库中依然没有生成数据表的问题
综合分析一下行程这个问题的原因: 在终端中运行 select * from django_migrations; 查看 提交的记录,如果你的表删掉了,记录还在,那么数据库会觉得,这个表依然是存在的,所 ...
- 微服务-dubbo学习
什么是微服务: 由于业务发展迅速,为了减少代码和功能重复,方便扩展,部署,维护等因素,将系统业务组件化和服务化拆分,拆分为一个个独立的服务,由服务治理系统统一管理,每个微服务为一个进程,之间的通讯方式 ...
- HTML实现页面自动跳转的五种方法
下面列了五个例子来详细说明,这几个例子的主要功能是:在5秒后,自动跳转到同目录下的hello.html(根据自己需要自行修改)文件. 1)html的实现 复制代码 代码如下: <head> ...
- 【365】拉格朗日乘子法与KKT条件说明
参考:知乎回答 - 通过山头形象描述 参考:马同学 - 如何理解拉格朗日乘子法? 参考: 马同学 - 如何理解拉格朗日乘子法和KKT条件? 参考:拉格朗日乘数 - Wikipedia 自己总结的规律 ...