一、fetch() 是什么?
fetch() 是 浏览器内置的 全局 JavaScript 方法,用于发出 http 请求,无需下载安装,可以直接使用。
// 一个简单 http 请求
fetch('http://example.com/movies.json')
.then(function (response) {
return response.json();
})
.then(function (myJson) {
console.log(myJson);
});
二、怎么使用?
1、简单使用实例
fetch() 的第二个参数是 init
对象,用于设置 http 的配置信息。
postData('http://example.com/answer', {
answer: 42 })
.then(data => console.log(data))
.catch(error => console.error(error))
function postData(url, data) {
return fetch(url, {
body: JSON.stringify(data),
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST',
mode: 'cors',
redirect: 'follow',
referrer: 'no-referrer',
})
.then(response => response.json())
}
2、配置详细说明
method
:请求使用的方法,如 GET、POST、PUT、DELETE 等。headers
:请求的头信息。body
:请求的 body 信息,注意 GET 或 HEAD 方法的请求不能包含 body 信息。mode
:请求模式,可用值: cors、no-cors、same-origincredentials
:是否发送 cookie 给服务器:omit(任何情况都不发)、same-origin(同源才发)、include(任何情况都发)cache
:可用 cache 模式 :default、no-store、reload、no-cache、force-cache、only-if-cached 。redirect
:重定向,Chrome中默认使用 follow ;- follow (自动重定向)
- error (发生重定向将自动终止并且抛出错误)
- manual (手动处理重定向)
referrer
:发送请求的页面URL,浏览器默认添加到请求Header 中。设置成no-referrer
表示不添加。referrerPolicy
:什么时候使用 referrer,可用值: no-referrer、 no-referrer-when-downgrade、origin、origin-when-cross-origin、unsafe-url 。integrity
:设定资源对应 hash 值,保证资源的完整性。
三、使用场景
1、发送带凭证请求
// 同不同源都会发送 带凭证的请求
fetch('https://example.com', {
credentials: 'include'
})
// 只有同源才发送 带凭证请求
fetch('https://example.com', {
credentials: 'same-origin'