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);
})