fetch:
實現ES的規范進行實現的而不是通過創建xml實現的
fetch屬於window的屬性(兼容性問題)
基於promiseAPI
whatwg-fetch
安裝
cnpm install whatwg-fetch -S
get請求
fetch("/users/login?username=123") .then((res)=>res.json()) .then(data=>{ console.log(data); })
post請求
fetch("/users/login",{
method:"post"
headers:{
"content-type":"application/x-www-form-urlecoded"
}
body:qs.stringfiy(存放post請求的時候提交的數據)
}).then((res)=>res.json)
.then(data=>{
console.log(data);
})
body請求數據的格式必須是數據序列化的格式化
qs模塊
{
username:"Alley",
age:19
}
username=alley&age=19
application/x-www-form-urlencode
fetch默認是不會攜帶cookie的
所以必須設置屬性credentials:include
注意:
fetch中第一個.then並不是成功的返回值而是一個未處理的結果集。需要根據自身的情況返回相對應
的解析結果一般情況下我們只需要調用res.json即可(意思是返回json類型的數據)
第二個.then中才是最終的返回結果