Fetch API是基于Promise实现的获取远端数据的方式,可以这么理解Fetch 就是XMLHttpRequest的升级版。
fetch(url)
.then(function(res){
})
.then(function(data){
})
典型用法:
fetch('http://192.168.101.100')
.then(function(res){
// res.text()和res.json() 返回值都是个Promise对象,我们一般将其值返回,在下一个then中接受数据
// 获取响应的信息,转成文本格式的Promise对象
return res.text();
// 获取响应的信息,转成json格式的Promise对象
// return res.json();
})
.then(function(data){
console.log(data);
})
其实fetch()
,可以有第二个参数,传入一些其它配置项,参数类型为对象:
fetch(url, options)
第二个参数: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
。为了在当前域名内自动发送 cookie , 必须提供这个选项, 从 Chrome 50 开始, 这个属性也可以接受FederatedCredential
实例或是一个PasswordCredential
实例。cache
: 请求的 cache 模式:default
、no-store 、
reload 、
no-cache 、
force-cache
或者only-if-cached 。
redirect
: 可用的 redirect 模式:follow
(自动重定向),error
(如果产生重定向将自动终止并且抛出一个错误), 或者manual
(手动处理重定向). 在Chrome中,Chrome 47之前的默认值是 follow,从 Chrome 47开始是 manual。referrer
: 一个USVString
,可以是no-referrer
、client
或一个URL。默认是client
。referrerPolicy
: Specifies the value of the referer HTTP header. May be one ofno-referrer、
no-referrer-when-downgrade、
origin、
origin-when-cross-origin、
unsafe-url 。
integrity
: 包括请求的 subresource integrity 值 ( 例如:sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=
)。
上面诸多options中,其实常用的就是method
、headers
、body
以及mode
等。
// get请求
fetch('/test2?name=哈哈')
// 默认是GET请求,直接使用querystring方式传参
.then(res =>{
return res.text();
})
.then(data=>{
console.log(data);
})
// delete请求
fetch('/test2', {
// 发送delete请求
method: 'DELETE'
})
.then(res =>{
return res.text();
})
.then(data=>{
console.log(data);
})
// POST 请求
// POST 请求传参的方式比较多 这里只是其中一种
fetch('/test', {
method: 'POST',
// 传递的数据主体
body: 'name=哈哈&age=18',
headers: {
// 必须传
'content-type': 'application/x-www-form-urlencoded'
}
})
.then(res =>{
return res.json();
})
.then(data=>{
console.log(data);
})
// put请求 传参方式一样,不过一般put方式用在restful风格的接口上,一般url地址会比较特殊
fetch('/test', {
method: 'PUT',
body: 'name=哈哈&age=18',
headers: {
// 必须传
'content-type': 'application/x-www-form-urlencoded'
}
})
.then(res =>{
return res.json();
})
.then(data=>{
console.log(data);
})