讲解顺序按照:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
目录
(1).语法Promise fetch(input[, init]);
3.可以通过HTML元素,FormData() 和fetch()上传文件。
4.上传多个文件可以通过HTML元素,FormData() 和fetch()上传文件。
1.Fetch接口. 跨网络异步获取资源
(https://developer.mozilla.org/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/fetch)
位于 WorkerOrGlobalScope
这一个 mixin 中的 fetch()
方法用于发起获取资源的请求。它返回一个 promise,这个 promise 会在请求响应后被 resolve,并传回 Response
对象。我们搜线要知道fetch是个全局或者worker的.
注意:fetch()
方法的参数与 Request()
构造器是一样的。
(1).语法
Promise<Response> fetch(input[, init]);
input:
init :
一个配置项对象,包括所有对请求的设置。可选的参数有:
1. method: 请求使用的方法,如 GET、POST。
2. headers: 请求的头信息,形式为 Headers 的对象或包含 ByteString 值的对象字面量。
3. body: 请求的 body 信息:可能是一个 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息。
4. mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
5. credentials: 请求的 credentials,如 omit、same-origin 或者 include。为了在当前域名内自动发送 cookie , 必须提供这个选项, 从 Chrome 50 开始, 这个属性也可以接受 FederatedCredential 实例或是一个 PasswordCredential 实例。
6. cache: 请求的 cache 模式: default 、 no-store 、 reload 、 no-cache 、 force-cache 或者 only-if-cached 。
7. redirect: 可用的 redirect 模式: follow (自动重定向), error (如果产生重定向将自动终止并且抛出一个错误), 或者 manual (手动处理重定向). 在Chrome中,Chrome 47之前的默认值是 follow,从 Chrome 47开始是 manual。
8. referrer: 一个 USVString 可以是 no-referrer、client或一个 URL。默认是 client。
9. referrerPolicy: 指定了HTTP头部referer字段的值。可能为以下值之一: no-referrer、 no-referrer-when-downgrade、 origin、 origin-when-cross-origin、 unsafe-url 。
10. integrity: 包括请求的 subresource integrity 值 ( 例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。
返回:
一个 Promise
,resolve 时回传 Response
对象。
抛出两个错误
类型 | 描述 |
---|---|
AbortError |
The request was aborted (using AbortController.abort() ). |
TypeError |
Since Firefox 43, fetch() will throw a TypeError if the URL has credentials, such as http://user:password@example.com . |
2.注意:
- 当接收到一个代表错误的 HTTP 状态码时,从
fetch()
返回的 Promise 不会被标记为 reject, 即使该 HTTP 响应的状态码是 404 或 500。相反,它会将 Promise 状态标记为 resolve (但是会将 resolve 的返回值的ok
属性设置为 false ),仅当网络故障时或请求被阻止时,才会标记为 reject。 fetch()
不会接受跨域 cookies;你也不能使用fetch()
建立起跨域会话。其他网站的Set-Cookie
头部字段将会被无视。fetch
不会发送 cookies。除非你使用了credentials的 初始化选项。(自2017年8月25日以后,默认的credentials政策变更为same-origin
。Firefox也在61.0b13版本中,对默认值进行修改)
3.先进行一个简单的fetch.
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
console.log(fetch('http://example.com/movies.json'))
fetch 捕捉返回的是一个promise对象.但是这个promise却是response.看来promise也有很多的细分.
当他使用两个参数的时候,我也不知道跑这个的网站到底有没有,显示404.估计又是瞎凑的.而且有跨源.我也不知道怎么解决跨源.这是以后的问题,今天之只对语法,而不从更广义的范围来说.
到这里为止,你大概已经知道了,但是header,request和response的疑问在你的脑海中挥之不去.但是你还是要强忍着不适应,甚至完全不知道,把这里看下去.
1.header https://blog.csdn.net/jiaoqi6132/article/details/104167584
2.request https://mp.csdn.net/postedit/104168535
3.body https://blog.csdn.net/jiaoqi6132/article/details/104169526
4.blob https://blog.csdn.net/jiaoqi6132/article/details/104170018
5.readablestream 暂时不写了...
6.response https://blog.csdn.net/jiaoqi6132/article/details/104170649
4.fetch更进一步
(1)发送带凭据的请求
为了让浏览器发送包含凭据的请求(即使是跨域源),要将credentials: 'include'
添加到传递给 fetch()
方法的init
对象。
fetch('https://example.com', {
credentials: 'include'
})
如果你只想在请求URL与调用脚本位于同一起源处时发送凭据,请添加credentials: 'same-origin'
。
// The calling script is on the origin 'https://example.com'
fetch('https://example.com', {
credentials: 'same-origin'
})
要改为确保浏览器不在请求中包含凭据,请使用credentials: 'omit'
。
fetch('https://example.com', {
credentials: 'omit'
})
(2).上传文件
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));
上传文件
3.可以通过HTML<input type="file" />
元素,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));
4.上传多个文件可以通过HTML<input type="file" mutiple/>
元素,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));
5.检测请求是否成功
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);
});
6.自定义请求对象
除了传给 fetch()
一个资源的地址,你还可以通过使用 Request()
构造函数来创建一个 request 对象,然后再作为参数传给 fetch().
clone()
方法也可以用于创建一个拷贝。它和上述方法一样,如果 request 或 response 的 body 已经被读取过,那么将执行失败。区别在于, clone()
出的 body 被读取不会导致原 body 被标记为已读取。
来源:CSDN
作者:树根朽木
链接:https://blog.csdn.net/jiaoqi6132/article/details/104166753