promise fetch axios
基于Promise发送Ajax
// 路由
app.get('/data', (req, res) => {
res.send('Hello World!')
})
function queryData(url) {
var p = new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) return;
if (xhr.readyState == 4 && xhr.status == 200) {
// 处理正常的情况
resolve(xhr.responseText);
} else {
// 处理异常情况
reject('服务器错误');
}
};
xhr.open('get', url);
xhr.send(null);
});
return p;
}
queryData('http://localhost:3000/data')
.then(function (data) {
console.log(data);
}, function (info) {
console.log(info)
});
基于Promise发送Ajax请求解决回调地狱
// 路由
app.get('/data', (req, res) => {
res.send('Hello World!')
})
app.get('/data1', (req, res) => {
setTimeout(function () {
res.send('Hello TOM!')
}, 1000);
})
app.get('/data2', (req, res) => {
res.send('Hello JERRY!')
})
............基于Promise发送Ajax...............
// 发送多个ajax请求并且保证顺序
queryData('http://localhost:3000/data')
.then(function(data){
console.log(data)
return queryData('http://localhost:3000/data1');
})
.then(function(data){
console.log(data);
return queryData('http://localhost:3000/data2');
})
.then(function(data){
console.log(data)
});
.then参数
............基于Promise发送Ajax...............
queryData('http://localhost:3000/data')
.then(function(data){
return queryData('http://localhost:3000/data1');
})
.then(function(data){
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve(123);
},1000)
});
})
.then(function(data){
console.log(data) //123
return 'hello';
})
.then(function(data){
console.log(data) //hello
})
Promise 基本API
实例方法
.then()
- 得到异步任务正确的结果
.catch()
- 获取异常信息
.finally()
- 成功与否都会执行(不是正式标准
/*
Promise常用API-实例方法
*/
// console.dir(Promise);
function foo() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
// resolve(123);
reject('error');
}, 100);
})
}
foo()
.then(function (data) {
console.log(data) //123
})
.catch(function (data) {
console.log(data) //error
})
.finally(function () {
console.log('finished') //finished
});
// --------------------------
// 两种写法是等效的
// foo()
// .then(function (data) {
// console.log(data) //123
// }, function (data) {
// console.log(data) //error
// })
// .finally(function () {
// console.log('finished') //finished
// });
静态方法
.all()
Promise.all
方法接受一个数组作参数,数组中的对象(p1、p2、p3)均为promise实例(如果不是一个promise,该项会被用Promise.resolve
转换为一个promise)。它的状态由这三个promise实例决定
.race()
Promise.race
方法同样接受一个数组作参数。当p1, p2, p3中有一个实例的状态发生改变(变为fulfilled
或rejected
),p的状态就跟着改变。并把第一个改变状态的promise的返回值,传给p的回调函数
app.get('/a1', (req, res) => {
setTimeout(function () {
res.send('Hello TOM!')
}, 1000);
})
app.get('/a2', (req, res) => {
setTimeout(function () {
res.send('Hello JERRY!')
}, 2000);
})
app.get('/a3', (req, res) => {
setTimeout(function () {
res.send('Hello SPIKE!')
}, 3000);
})
............基于Promise发送Ajax...............
var p1 = queryData('http://localhost:3000/a1');
var p2 = queryData('http://localhost:3000/a2');
var p3 = queryData('http://localhost:3000/a3');
Promise.all([p1, p2, p3]).then(function (result) {
console.log(result) //["Hello TOM!", "Hello JERRY!", "Hello SPIKE!"]
})
// Promise.race([p1,p2,p3]).then(function(result){
// console.log(result) //Hello TOM!
// })
fetch API 中的 HTTP 请求
- fetch(url, options).then()
- HTTP协议,它给我们提供了很多的方法,如POST,GET,DELETE,UPDATE,PATCH和PUT
- 默认的是 GET 请求
- 需要在 options 对象中 指定对应的 method method:请求使用的方法
- post 和 普通 请求的时候 需要在options 中 设置 请求头 headers 和 body
Fetch API 基本用法
app.get('/fdata', (req, res) => {
res.send('Hello Fetch!')
})
fetch('http://localhost:3000/fdata').then(function(data){
// text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取后台返回的数据
return data.text();
}).then(function(data){
console.log(data); //Hello Fetch!
})
Fetch API 调用接口传递参数
后台
// 设置允许跨域访问该服务
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,Content-Type,mytoken");
next();
});
app.get('/books', (req, res) => {
res.send('传统的URL传递参数!' + req.query.id)
})
app.get('/books/:id', (req, res) => {
res.send('Restful形式的URL传递参数!' + req.params.id)
})
app.delete('/books/:id', (req, res) => {
res.send('DELETE请求传递参数!' + req.params.id)
})
app.post('/books', (req, res) => {
res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd)
})
app.put('/books/:id', (req, res) => {
res.send('PUT请求传递参数!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})
// app.get('/books', (req, res) => {
// res.send('传统的URL传递参数!' + req.query.id)
// })
// app.get('/books/:id', (req, res) => {
// res.send('Restful形式的URL传递参数!' + req.params.id)
// })
// app.delete('/books/:id', (req, res) => {
// res.send('DELETE请求传递参数!' + req.params.id)
// })
// app.post('/books', (req, res) => {
// res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd)
// })
// app.put('/books/:id', (req, res) => {
// res.send('PUT请求传递参数!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
// })
// GET参数传递-传统URL
// fetch('http://localhost:3000/books?id=123', {
// method: 'get'
// })
// .then(function (data) {
// return data.text();
// }).then(function (data) {
// console.log(data) //08-FetchAPI参数传递.html:35 传统的URL传递参数!123
// });
// GET参数传递-restful形式的URL
// fetch('http://localhost:3000/books/456', {
// method: 'get'
// })
// .then(function (data) {
// return data.text();
// }).then(function (data) {
// console.log(data) //Restful形式的URL传递参数!456
// });
// DELETE请求方式参数传递
// fetch('http://localhost:3000/books/789', {
// method: 'delete'
// })
// .then(function (data) {
// return data.text();
// }).then(function (data) {
// console.log(data) //DELETE请求传递参数!789
// });
// POST请求传参
// fetch('http://localhost:3000/books', {
// method: 'post',
// body: 'uname=lisi&pwd=123',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
// }
// })
// .then(function (data) {
// return data.text();
// }).then(function (data) {
// console.log(data) //POST请求传递参数!lisi---123
// });
// POST请求传参 有问题将跨域拦截写到一行上
// fetch('http://localhost:3000/books', {
// method: 'post',
// body: JSON.stringify({
// uname: '张三',
// pwd: '456'
// }),
// headers: {
// 'Content-Type': 'application/json'
// }
// })
// .then(function (data) {
// return data.text();
// }).then(function (data) {
// console.log(data) //POST请求传递参数!张三---456
// });
// // PUT请求传参
fetch('http://localhost:3000/books/123', {
method: 'put',
body: JSON.stringify({
uname: '张三',
pwd: '789'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function (data) {
return data.text();
}).then(function (data) {
console.log(data) //PUT请求传递参数!123---张三---789
});
Fetch响应结果的数据格式
app.get('/json', (req, res) => {
res.json({
uname: 'lisi',
age: 13,
gender: 'male'
});
})
fetch('http://localhost:3000/json').then(function(data){
// return data.json();
return data.text();
}).then(function(data){
// console.log(data.uname)
// console.log(typeof data)
var obj = JSON.parse(data);
console.log(obj.uname,obj.age,obj.gender) //lisi 13 male
})
axios基本使用
基本使用
app.get('/adata', (req, res) => {
res.send('Hello axios!')
})
axios.get('http://localhost:3000/adata').then(function (ret) {
// 注意data属性是固定的用法,用于获取后台的实际数据
console.log(ret.data) //Hello axios!
console.log(ret)
})
axios请求参数
后台
app.get('/axios', (req, res) => {
res.send('axios get 传递参数' + req.query.id)
})
app.get('/axios/:id', (req, res) => {
res.send('axios get (Restful) 传递参数' + req.params.id)
})
app.delete('/axios', (req, res) => {
res.send('axios get 传递参数' + req.query.id)
})
app.post('/axios', (req, res) => {
res.send('axios post 传递参数' + req.body.uname + '---' + req.body.pwd)
})
app.put('/axios/:id', (req, res) => {
res.send('axios put 传递参数' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})
// axios get请求传参
// axios.get('http://localhost:3000/axios?id=123').then(function (ret) {
// console.log(ret.data) //axios get 传递参数123
// })
// axios.get('http://localhost:3000/axios/123').then(function (ret) {
// console.log(ret.data) //axios get (Restful) 传递参数123
// })
// axios.get('http://localhost:3000/axios', {
// params: {
// id: 789
// }
// }).then(function (ret) {
// console.log(ret.data) //axios get 传递参数789
// })
// axios delete 请求传参
// axios.delete('http://localhost:3000/axios', {
// params: {
// id: 111
// }
// }).then(function (ret) {
// console.log(ret.data) //axios get 传递参数111
// })
// axios.post('http://localhost:3000/axios', {
// uname: 'lisi',
// pwd: 123
// }).then(function (ret) {
// console.log(ret.data) //axios post 传递参数lisi---123
// })
// var params = new URLSearchParams();
// params.append('uname', 'zhangsan');
// params.append('pwd', '111');
// axios.post('http://localhost:3000/axios', params).then(function (ret) {
// console.log(ret.data) //axios post 传递参数zhangsan---111
// })
// axios put 请求传参
axios.put('http://localhost:3000/axios/123', {
uname: 'lisi',
pwd: 123
}).then(function (ret) {
console.log(ret.data) //axios put 传递参数123---lisi---123
})
axios 响应结果与全局配置
app.get('/axios-json', (req, res) => {
res.json({
uname: 'lisi',
age: 12
});
})
axios.get('http://localhost:3000/axios-json').then(function (ret) {
console.log(ret.data.uname) //LISI
})
// 配置请求的基准URL地址
axios.defaults.baseURL = 'http://localhost:3000/';
// 配置请求头信息
axios.defaults.headers['mytoken'] = 'hello';
axios.get('axios-json').then(function (ret) {
console.log(ret.data.uname) //LISI
})
axios拦截器
# 1. 请求拦截器
axios.interceptors.request.use(function(config) {
console.log(config.url) //http://localhost:3000/adata
# 1.1 任何请求都会经过这一步 在发送请求之前做些什么
config.headers.mytoken = 'nihao';
# 1.2 这里一定要return 否则配置不成功
return config;
}, function(err){
#1.3 对请求错误做点什么
console.log(err)
})
#2. 响应拦截器
axios.interceptors.response.use(function(res) {
#2.1 在接收响应做些什么
var data = res.data;
return data;
}, function(err){
#2.2 对响应错误做点什么
console.log(err)
})
async 和 await
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-r2U01Ysw-1622355023575)(C:\Users\Shinelon\AppData\Roaming\Typora\typora-user-images\1619175098660.png)]
- async作为一个关键字放到函数前面
- 任何一个
async
函数都会隐式返回一个promise
- 任何一个
await
关键字只能在使用async
定义的函数中使用- await后面可以直接跟一个 Promise实例对象
- await函数不能单独使用
- async/await 让异步代码看起来、表现起来更像同步代码
# 1. async 基础用法
# 1.1 async作为一个关键字放到函数前面
async function queryData() {
# 1.2 await关键字只能在使用async定义的函数中使用 await后面可以直接跟一个 Promise实例对象
var ret = await new Promise(function(resolve, reject){
setTimeout(function(){
resolve('nihao')
},1000);
})
// console.log(ret.data)
return ret;
}
# 1.3 任何一个async函数都会隐式返回一个promise 我们可以使用then 进行链式编程
queryData().then(function(data){
console.log(data)
})
#2. async 函数处理多个异步函数
axios.defaults.baseURL = 'http://localhost:3000';
async function queryData() {
# 2.1 添加await之后 当前的await 返回结果之后才会执行后面的代码
var info = await axios.get('async1');
#2.2 让异步代码看起来、表现起来更像同步代码
var ret = await axios.get('async2?info=' + info.data);
return ret.data;
}
queryData().then(function(data){
console.log(data)
})
)
return ret;
}
# 1.3 任何一个async函数都会隐式返回一个promise 我们可以使用then 进行链式编程
queryData().then(function(data){
console.log(data)
})
#2. async 函数处理多个异步函数
axios.defaults.baseURL = 'http://localhost:3000';
async function queryData() {
# 2.1 添加await之后 当前的await 返回结果之后才会执行后面的代码
var info = await axios.get('async1');
#2.2 让异步代码看起来、表现起来更像同步代码
var ret = await axios.get('async2?info=' + info.data);
return ret.data;
}
queryData().then(function(data){
console.log(data)
})
###