vue基础4——fetch&axios
1. fetch
why:
XMLHttpRequest 是一个设计粗糙的 API,配置和调用方式非常混乱,
而且基于事件的异步模型写起来不友好。
兼容性不好
get
//fetch get
fetch("json/test.json?name=kerwin&age=100").then(res=>{
// console.log(res.json())
//拿到的是 状态码
// return a.text() // 文本格式
return res.json() //json格式
}).then(res=>{
console.log(res.data.films)
this.datalist = res.data.films
}).catch(err=>{
console.log(err)
})
post-1
form 编码 ,name=kerwin&age=100
fetch("json/test.json",{
method:"post",
headers:{
"Content‐Type": "application/x‐www‐form‐urlencoded"
},
body:"name=kerwin&age=100" //请求体
}).then(res=>res.json()).then(res=>{
console.log(res)
})
post-2
json 编码 ,"{name:'kerwin',age:100}"
fetch("json/test.json",{
method:"post",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
name:"kerwin",
age:100
}) //请求体
}).then(res=>res.json()).then(res=>{
console.log(res)
})
注意:
Fetch 请求默认是不带 cookie 的,需要设置 fetch(url, {credentials:'include'})
fetch("**",{
credentials:"include",
method:'post',
headers: {
"Content‐Type": "application/x‐www‐form‐urlencoded"
},
body: "name=kerwin&age=100",
}).then(res=>res.json()).then(res=>{console.log(res)});
2. axios
https://github.com/axios/axios
axios.get("json/test.json?name=kerwin&age=100").then(res=>{
// res.data 才是真正的后端数据
console.log(res.data.data.films)
this.datalist= res.data.data.films
})
post -1- x-www-form-urlencode
axios.post("json/test.json","name=kerwin&age=100").then(res=>{
console.log(res.data)
})
post -2- application/json
axios.post("json/test.json",{
name:"kerwin",
age:100
}).then(res=>{
console.log(res.data)
})
浙公网安备 33010602011771号