Fetch 用法
promise
promise是es6中的对象
promise <->成功/失败 异步
new Promise((resolve,reject)=>{
//resolve 成功 reject 失败
resolve(num)//将会走成功的then回调
reject(num)//将会走失败的then回调
}).then((num)=>{
alert('成功',num)
},(num)=>{
alert('失败',num)
})
Fetch
<input type="text" name="" id="username"><br>
<input type="password" name="" id="psw">
<button class="login">
登录
</button>
get
document.querySelector('.login')['onclick']=x=>{
fetch(`http//localhost:8080/login?user=${user.value}&psw=${psw.value}`,{
method:'GET'
}).then((res)=>{
res.json(()=>{//这是一个promise实例
}).then(()=>{//成功
}).catch(()=>{//失败
console.log('服务器错误')
})
})
}
post
document.querySelector('.login')['onclick']=x=>{
fetch(`http//localhost:8080/login`,{
method:'POST',
headers:{
'Content-Type':'application/x-www-form-urlencoded'//需要声明 传字符串
}
body:`user=${user.value}&psw=${psw.value}`//非明文
}).then((res)=>{
res.json(()=>{
}).then(()=>{//成功
//做事
}).catch(()=>{//失败
console.log('服务器错误')
})
})
}
传图片
头像<input type="file" id="fl">
document.querySelector('.login')['onclick']=x=>{
//console.log(fl.files[0])
let fd = new FormData()
fd.append('pic',fl.files[0])
fetch('http//localhost:8080/login',{
method:'POST',
body:fd,
}).then((res)=>{
}).then((res)=>{
var {ok} = res
if(ok){
let {dataUrl} = res;
console.log(dataUrl)
}
}).catch(()=>{
console.log("服务器错误")
})
}