前端(Axios和Promis)
Promise
语法
<script>
// 创建promise对象
// 此函数需要再传入两个参数,都是函数类型
let p=new Promise((resolve,reject)=>{
if(3>2){
resolve({name:"李思蕾",age:23,地址:"河南省"});
}else{
reject("error");
}
});
console.log(p);
p.then((o)=>{
console.log(o)
},(e)=>{
console.log(e)
})
</script>
Promise封装Ajax
<script>
let p=new Promise((resolve,reject)=>{
let xhr=new XMLHttpRequest();
xhr.open("get","https://jsonplaceholder.typicode.com/users");
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
resolve(xhr.response);
}else{
reject("获取失败")
}
}
}
});
p.then(a=>{
console.log(a)
},b=>{
console.log(b)
})
</script>
Axios
语法
服务器Server.js(处理请求,并响应数据)
<script>
let data=axios.get("http://localhost:3000",{params:{name:"李四",age:24}})
data.then((a)=>{
console.log(a.data)//请求成功后的数据
},(b)=>{
console.log("error")//请求失败后提示
})
</script>
客户端向服务器发送请求
<script>
let person=[{name:"李四",age:24},{name:"李四",age:24},{name:"李四",age:24},{name:"李四",age:24},{name:"李四",age:24},{name:"李四",age:24},{name:"李四",age:24}]
let data=axios.get("http://localhost:3000",{params:person})
data.then((a)=>{
console.log(a.data)//请求成功后的数据
},(b)=>{
console.log("error")//请求失败后提示
})
</script>
优化后Axios写法
<script>
let person=[{name:"王五",age:24}]
let http=axios.create({
baseURL:'http://localhost:3000'
});
let p= http.get("",{params:person})
p.then((a)=>{
console.log(a.data)//请求成功后的数据
},(b)=>{
console.log("error")//请求失败后提示
})
</script>
拦截器
<script>
let person=[{name:"王五",age:24}]
let http=axios.create({
baseURL:'http://localhost:3000'
});
http.interceptors.request.use((request)=>{
return request
})
http.interceptors.response.use((response)=>{
return response.data;
})
let p=http.get("",{params:person})
p.then((a)=>{
console.log(a)//请求成功后的数据
},(b)=>{
console.log("error")//请求失败后提示
})
</script>
原文地址:https://blog.csdn.net/m0_67244960/article/details/144446351
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!