promise
promise常用的API
1.then获取异步的正确结果
function queryData(){
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve('成功接收参数');
},1000)
})
}
queryData().then(function(data){
console.log(data)
})
2.catch获取错误结果
function queryData(){
return new Promise(function(reslove,reject){
setTimeOut(function(){
reject('error');
})
})
}
queryData().catch(function(data){
console.log(data);
})
3.finally正确与否都会执行
function queryData(){
let p = new Promise(resolve,reject){
setTimeout(function(){
reslove('success');
},1000)
}
}
// 调用queryData()
queryData().then(function(data){
console.log(data)
})
.finally(function(data){
console.log('tip');
})
发送Ajax
function queryData(){
var p = new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.onReadyChange = function(){
if(xhr.readyState!=4) return null;
if(xhr.status==200 && xhr.readyState==4){
reslove(xhr.responseText());
}else{
reject('服务器错误')
}
}
xhr.open('get',url);
xhr.send(null)
})
return p;
}
// 调用queryData 处理异步请求
queryData('http://127.0.0.1:3000/index')
.then(function(data){
console.log(data);
})
发送多个Ajax请求
优点:减少回调地狱
queryData('htto://127.0.0.1:3000/index')
.then(function(data){
console.log(data);
return queryData('http://127.0.0.1:3000/user')
})
.then(function(data){
// 获取 queryData('http://127.0.0.1:3000/user') 的异步信息
console.log(data)
return queryData('http://127.0.0.1:3000/login');
})
.then(function(data){
// 获取queryData('http://127.0.0.1:3000/login')的异步信息
console.log(data);
})
jQuery
嵌套性
不太便于阅读
$.ajax({
url:'http://127.0.0.1:3000/index',
type:'get',
success:function(data){
console.log(data);
$.ajax({
url:'http://127.0.0.1:3000/user',
type:'get',
success:function(data){
console.log(data);
$.ajax({
url:'http://127.0.0.1:3000/login',
type:'get',
success:function(data){
console.log(data);
}
})
}
})
}
})
对象方法
all
function queryData(url){
return new Promise(function(reslove,reject){
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState!=4) return null;
if(xhr.readyState==4&&xhr.status==200){
reslove(xhr.responseText);
}else{
reject('服务器错误');
}
}
xhr.open('get',url);
xhr.send(null);
})
}
var p1 = queryData('http://127.0.0.1:3000/a1');
var p2 = queryData('http://127.0.0.1:3000/a2');
var p3 = queryData('http://127.0.0.1:3000/a3');
Promise.all([p1,p2,p3])
.then(function(result){
console.log(result);
})
执行所有异步请求后,才可以得到结果
race
var p1 = queryData('http://127.0.0.1:3000/a1');
var p2 = queryData('http://127.0.0.1:3000/a2');
var p3 = queryData('http://127.0.0.1:3000/a3');
Promise.race([p1,p2,p3])
.then(function(result){
console.log(result);
})
执行一个异步任务
就可以返回结果
node
const express = require('express');
const app = express();
// 设置跨域资源共享
app.all('*',function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Methods","PUT,GET,POST,DELETE.OPTIONS");
res.header("Access-Control-Allow-Headers","X-Requested-With");
res.header("Access-Control-Allow-Headers","Content-Type");
res.header("Access-Control-Allow-Headers","mytoken");
next();
})
app.get('/a1',function(req,res){
setTimeout(function(){
res.send('hello world')
},1000);
});
app.get('/a2',function(req,res){
setTimeout(function(){
res.send('hello Dack')
},1000);
});
app.get('/a1',function(req,res){
setTimeout(function(){
res.send('hello Hack')
},1000);
});
app.listen(3000,function(){
console.log('server running at http://127.0.0.1:3000');
})
fetch
常用的配置项
method 请求方法
get post put delete
body HTTP 请求参数
headers 请求头
相应结果
.text() 将返回体处理为字符串类型
.json() 将返回体处理为json类型
method:get
fetch('http://127.0.0.1:3000/login').then(data=>{
// 返回的是promise 实例对象
return data.text()
}).then(data=>{
console.log(data)
})
method:post
传统方式的传递参数
如果接受的数据为json格式的话,需要使用JSON.parse()转化为json格式
fetch('http://127.0.0.1:3000/register',{
method:'post',
body:'uname=zhangsan&pwd=122345',
headers:{
'Content-Type':'application/x-www-urlencoded'
}
}).then(data=>{
return data.text()
}).then(data=>{
// 接受的数据为json形式
var obj = JSON.parse(data);
console.log(obj);
})
method:post
json方式传递参数
fetch('http://127.0.0.1:3000/register',{
method:'post',
body:JSON.stringify({
user_name:'张三',
pwd:'1234'
}),
headers:{
'COntent-Type':'application/json'
}
}).then(data=>{
return data.json()
}).then(data=>{
console.log(data)
})
axios
概念
Axios 一个基于Promise的HTTP组件库(官方)
优点
1.从浏览器中创建XML HttpRequest
2.自动转化为JSON格式
3.客服端支持防御XSRF攻击
安装
npm
npm install axios -S
bower
$bower install axios
cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
基本用法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./src/axios.js"></script>
</head>
<body>
<script>
axios.get('http://127.0.0.1:3000/adata').then(ret=>{
console.log(ret.data);
})
</script>
</body>
</html>
node
const express = require('express');
const badyParse = requires('body-parse');
// 处理数据
app.use(badyParse.json());
app.use(badyParse.urlencoded({extend:false}));
const app = express();
// 允许跨域资源共享
app.all(*,function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Methods","PUT,GET,POST,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers","X-Requested-With");
res.header("Access-Control-Allow-Headers","Content-Type");
res.header("Access-Control-Allow-Headers","mytoken");
next();
})
app.get('/adata',(req,res)=>{
res.send('Hello Axios');
})
// 启动服务器
app.lisetn(3000,function(){
console.log('server running at http://127.0.0.1:3000');
})
axios 常用的API
get post put delete
全局配置
// 超时时间
axios.defaults.timeout=3000;
// 默认地址
axios.defaults.baseURL='http://127.0.0.1:3000/';
// 配置请求头
axios.defaults.headers['mytoken']='hello';
响应结果的主要属性
.data 实际响应的数据
.statusText:响应状态信息
.status 状态码
.headers 响应头信息
axios 拦截器
请求拦截器
对请求数据进行拦截处理
axios.interceptros.requset.use(function(config){
console.log(config);
// 对响应头中的mytoken 值进行更改
config.headers.mytoken='world'
return config;
},function(err){
console.log(err);
})
响应拦截器
对请求成功的数据进行操作
<script>
axios.interceptors.response.use(function(res){
var ret = res.data;
return ret;
},function(err){
console.log(err);
})
</script>
注意:请求/响应 拦截器要写在发送请求之前
// 配置默认地址
axios.defaults.baseURL='http://127.0.0.1:3000/';
// 配置请求头
axios.defaults['mytoken']='hello';
axios.interceptors.request.use(function(config){
// 对请求头中的mytoken 中的值进行修改
config.headers.mytoken='world';
return config;
}.function(err){
console.log(err)
})
axios.interceptors.response.use(function(res){
var ret = res.data;
return ret;
},function(err){
console.log(err);
})
axios.get('users').then(data=>{
console.log(data);
})