接口调用方式
异步编程
- 异步
// 回调地狱
$.ajax({
url: 'http://localhost:3000/data',
success: function(data){
console.log(data);
$.ajax({
url: 'http://localhost:3000/data1',
success: function(data){
console.log(data);
$.ajax({
url: 'http://localhost:3000/data2',
success: function(data){
console.log(data);
}
});
}
});
}
});
异步编程Promise
用法详解
-
Promise
概述 -
Promise
好处- 可以避免多层异步调用嵌套问题(回调地狱)
- Promise对象提供了简介的API,使得控制异步操作更加容易
Promise基本使用
// Promise基本使用
var p = new Promise(function(resolve, reject){
// 这里用于实现异步任务
setTimeout(function(){
var flag = true;
if(flag) {
resolve('hello');
}else{
reject('出错了');
}
}, 100);
});
p.then(function(data){
console.log(data);
},function(info){
console.log(info);
})
Promise发送Ajax请求并处理回调地狱问题
- 基于Promise发送Ajax请求
function queryData(url) {
// 1.1 创建一个Promise实例
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) {
// 1.2 处理正常的情况
resolve(xhr.responseText);
}else{
// 1.3 处理异常情况
reject('服务器错误');
}
};
xhr.open('get', url);
xhr.send(null);
});
return p;
}
// 注意:这里需要开启一个服务
// 在then方法中,你也可以直接return数据而不是Promise对象
// 在后面的then中就可以接收到数据了
queryData('http://localhost:3000/data0')
.then(function(data){
console.log(data)
// 1.4 想要继续链式编程下去 需要 return
return queryData('http://localhost:3000/data1');
},function(info){
console.log(info);
return queryData('http://localhost:3000/data1');
})
.then(function(data){
console.log(data);
return queryData('http://localhost:3000/data2');
},function(info){
console.log(info);
return queryData('http://localhost:3000/data2');
})
.then(function(data){
console.log(data);
return '数据调用结束!';
},function(info){
console.log(info);
return '数据调用结束!';
})
.then(function(data){
console.log(data);
});
then方法参数中函数的返回值
function queryData(url) {
// 1.1 创建一个Promise实例
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState != 4) return;
if(xhr.readyState == 4 && xhr.status == 200) {
// 1.2 处理正常的情况
resolve(xhr.responseText);
}else{
// 1.3 处理异常情况
reject('服务器错误');
}
};
xhr.open('get', url);
xhr.send(null);
});
}
// 注意:这里需要开启一个服务
// 在then方法中,你也可以直接return数据而不是Promise对象
// 在后面的then中就可以接收到数据了
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('数据调用成功!);
},1000)
})
})
.then(function(data){
console.log(data);
return '数据调用结束!'
})
.then(function(data){
console.log(data);
});
Promise常用API
function foo() {
return new Promise(function(resolve, reject){
setTimeout(function(){
// resolve(123);
reject('error');
}, 100);
})
}
foo()
.then(function(data){
console.log(data)
})
.catch(function(data){
console.log(data)
})
.finally(function(){
console.log('finished')
});
// 等效写法
function foo() {
return new Promise(function(resolve, reject){
setTimeout(function(){
// resolve(123);
reject('error');
}, 100);
})
}
foo()
.then(function(data){
// 得到异步任务正确的结果
console.log(data)
},function(data){
// 获取异常信息
console.log(data)
})
// 成功与否都会执行(不是正式标准)
.finally(function(){
console.log('finished')
});
-
对象方法
Promise.all()
并发处理多个异步任务,所有任务都执行完成才能得到结果Promise.race()
并发处理多个异步任务,只要有一个任务完成就能得到结果
-
Promise.all()
-
Promise.race()
function queryData(url) {
return 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);
});
}
var p1 = queryData('http://localhost:3000/data');
var p2 = queryData('http://localhost:3000/data1');
var p3 = queryData('http://localhost:3000/data2');
// all中的参数[p1,p2,p3]和返回的结果一一对应
// ["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"]
Promise.all([p1, p2, p3]).then(function(res){
console.log(res);
});
//由于p1执行较快,Promise的then()将获得结果
// 'P1'。p2,p3仍在继续执行,但执行结果将被丢弃。
Promise.race([p1, p2, p3]).then(function(res){
console.log(res);
});
FetchAPI概述与基本使用
-
Fetch概述
-
语法结构
- Fetch API是新的ajax解决方案 Fetch会返回Promise
- fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象
- fetch(url, options).then()
fetch(url).then(fn2)
.then(fn3)
.then(fn)
接口调用fetch用法
fetch
基本用法
fetch('http://localhost:3000/fdata')
.then(function(data){
return data.text();
})
.then(function(data){
console.log(data);
})
fetch请求参数
-
常用配置选项
-
fetch API中的HTTP请求
-
服务器端配置方面
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
// 处理静态资源
app.use(express.static('public'))
// 处理参数 获取POST过来的数据
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// 设置允许跨域访问该服务
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', 'mytoken']);
// res.header('Access-Control-Allow-Headers', 'mytoken'); //出错根源
next();
});
// 路由代码
// 启动监听
app.listen(3000, () => {
console.log('网络服务器已运营...')
})
- GET请求方式的参数传递
// 案例对比
fetch('/abc?id=123')
.then(data => {
return data.text();
}).then(ret => {
// 注意:这里是刚才得到的数据
console.log(ret);
})
fetch('/abc/123', {
method: 'get'
}).then(data => {
return data.text();
}).then(ret => {
// 注意:这里是刚才得到的数据
console.log(ret);
})
// GET参数传递 - 传统URL 通过url ?的形式传参
fetch('http://localhost:3000/books?id=123', {
method: 'get' // get 请求可以省略不写 默认的是GET
})
.then(function(data) {
// 它返回一个Promise实例对象,用于获取后台返回的数据
return data.text();
}).then(function(data) {
// 在这个then里面我们能拿到最终的数据
console.log(data)
});
// 后台路由接口
app.get('/books', (req, res) => {
res.send('传统的URL传递参数!' + req.query.id)
})
// GET参数传递 - restful形式的URL 通过 / 的形式传递参数
// 即 id = 456 和id后台的配置有关
fetch('http://localhost:3000/books/456', {
method: 'get' // get 请求可以省略不写 默认的是GET
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
// 后台路由接口
app.get('/books/:id', (req, res) => {
res.send('Restful形式的URL传递参数!' + req.params.id)
})
- DELETE请求方式的参数传递
// DELETE请求方式参数传递
// 删除id 是 id=789
fetch('http://localhost:3000/books/789', {
method: 'delete'
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
// 后台路由接口
app.delete('/books/:id', (req, res) => {
res.send('DELETE请求传递参数!' + req.params.id);
})
- POST请求方式的参数传递
// POST请求方式参数传递
fetch('http://localhost:3000/books', {
method: 'post',
body: 'uname=sunny&pwd=123', // 传递数据
headers: { // 设置请求头
'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data);
});
// 后台路由接口
app.post('/books', (req, res) => {
res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd);
})
// POST请求方式参数传递
fetch('http://localhost:3000/books', {
method: 'post',
body: JSON.stringify({
uname: 'sunny',
pwd: '456'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data);
});
// 后台路由接口
app.post('/books', (req, res) => {
res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd);
})
- PUT请求方式的参数传递
- 和
POST
方式类似,也是两种方式
- 和
// 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)
});
// 后台路由接口
app.put('/books/:id', (req, res) => {
res.send('PUT请求传递参数!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})
FetchAPI响应数据格式
-
fetch API中的响应格式
-
响应数据格式
text()
将返回体处理成字符串类型json()
返回结果和JSON.parse(responseText)一样
/* Fetch响应结果的数据格式 text() */
fetch('http://localhost:3000/json').then(function(data){
return data.text(); // // 将获取到的数据 转换成字符串
}).then(function(data){
var obj = JSON.parse(data);
console.log(data);
console.log(data.uname,data.age);
console.log(typeof data); // string
console.log(obj.uname,obj.age,obj.gender);
})
/* Fetch响应结果的数据格式 json() */
fetch('http://localhost:3000/json').then(function(data){
return data.json(); // 将获取到的数据使用 json 转换对象
}).then(function(data){
console.log(data);
console.log(data.uname);
console.log(typeof data); // object
})
axios概述与基本用法
axios基本用法
-
get
和delete
请求传递参数- 通过传统的url 以 ? 的形式传递参数
- restful 形式传递参数
- 通过params 形式传递参数
-
post
和put
请求传递参数- 通过选项传递参数
- 通过
URLSearchParams
传递参数
-
发送
get
请求
// 发送get请求
axios.get('http://localhost:3000/adata')
.then(function(ret){
console.log(ret.data);
console.log(ret);
})
// 后台接口代码
app.get('/adata', (req, res) => {
res.send('Hello axios!');
})
axios常用API
-
常用API
-
get
请求传递参数- 通过传统的url 以 ? 的形式传递参数
restful
形式传递参数- 通过
params
形式传递参数
// 通过传统的url 以 ? 的形式传递参数
axios.get('http://localhost:3000/axios?id=123')
.then(function(ret){
console.log(ret.data);
})
// 后台代码
app.get('/axios', (req, res) => {
res.send('axios get 传递参数' + req.query.id)
})
// restful 形式传递参数
axios.get('http://localhost:3000/axios/123')
.then(function(ret){
console.log(ret.data);
})
// 后台代码
app.get('/axios/:id', (req, res) => {
res.send('axios get (Restful) 传递参数' + req.params.id)
})
// 通过params 形式传递参数
axios.get('http://localhost:3000/axios', {
params: {
id: 789
}
}).then(function(ret){
console.log(ret.data)
})
// 后台代码
app.get('/axios', (req, res) => {
res.send('axios get 传递参数' + req.query.id)
})
delete
请求传递参数- 传参的形式和 get 请求一样
// 通过params 形式传递参数
axios.delete('http://localhost:3000/axios', {
params: {
id: 111
}
}).then(function(ret){
console.log(ret.data)
})
// 后台代码
app.delete('/axios', (req, res) => {
res.send('axios get 传递参数' + req.query.id)
})
post
请求传递参数- 通过选项传递参数
- 通过
URLSearchParams
传递参数
// 通过选项传递参数
axios.post('http://localhost:3000/axios', {
uname: 'sunny',
pwd: 123
}).then(function(ret){
console.log(ret.data);
})
// 后台代码
app.post('/axios', (req, res) => {
res.send('axios post 传递参数' + req.body.uname + '---' + req.body.pwd);
})
// 通过选项传递参数
var params = new URLSearchParams();
params.append('uname', 'Tom');
params.append('pwd', '025');
axios.post('http://localhost:3000/axios', params).then(function(ret){
console.log(ret.data);
})
// 后台代码
app.post('/axios', (req, res) => {
res.send('axios post 传递参数' + req.body.uname + '---' + req.body.pwd);
})
put
请求传递参数- 和
post
请求一样
- 和
// 通过选项传递参数
axios.put('http://localhost:3000/axios/123', {
uname: 'Jerry',
pwd: 123567
}).then(function(ret){
console.log(ret.data);
})
// 后台代码
app.put('/axios/:id', (req, res) => {
res.send('axios put 传递参数' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})
axios的响应结果
- 响应结果的主要属性
data
实际响应回来的数据headers
响应头信息status
响应状态码statusText
响应状态信息
// 响应 字符串 数据
axios.get('http://localhost:3000/axios?id=987')
.then(function(ret){
console.log(typeof ret.data);
console.log(ret.data);
console.log(ret);
})
// 后端代码
app.get('/axios', (req, res) => {
res.send('axios get 传递参数' + req.query.id)
})
// 响应 对象 数据
axios.get('http://localhost:3000/axios-json')
.then(function(ret){
console.log(typeof ret.data);
console.log(ret.data);
console.log(ret);
})
// 后端代码
app.get('/axios-json', (req, res) => {
res.json({
uname: 'Jerry',
age: 12
});
})
axios的全局配置
-
配置 默认地址
axios.defaults.baseURL = 'https://api.example.com';
-
配置 超时时间
axios.defaults.timeout = 2500;
-
配置 公共请求头
-
配置 公共的
post
的Content-Type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
/* axios响应结果与全局配置 */
// 配置 超时时间
axios.defaults.timeout = 10;
// 配置请求的基准URL地址
axios.defaults.baseURL = 'http://localhost:3000';
// 配置请求头信息
axios.defaults.headers.common['mytoken'] = 'hello';
axios.get('axios-json')
.then(function(ret){
console.log(ret.data);
})
axios拦截器
axios.interceptors.request.use(function(config) {
console.log(config.url)
// 任何请求都会经过这一步 在发送请求之前做些什么
config.headers.mytoken = 'nihao';
// 这里一定要return 否则配置不成功
return config;
}, function(err){
// 对请求错误做点什么
console.log(err)
})
axios.get('http://localhost:3000/adata')
.then(function(data){
console.log(data);
})
axios.interceptors.response.use(function(res) {
// 在接收响应做些什么
var data = res.data;
return data;
}, function(err){
// 对响应错误做点什么
console.log(err)
})
axios.get('http://localhost:3000/adata')
.then(function(data){
console.log(data);
})
axios.interceptors.request.use(function(config) {
console.log(config.url);
// 任何请求都会经过这一步 在发送请求之前做些什么
config.headers.mytoken = 'success';
// 这里一定要return 否则配置不成功
return config;
}, function(err){
// 对请求错误做点什么
console.log(err)
})
axios.interceptors.response.use(function(res) {
// 在接收响应做些什么
var data = res.data;
console.log(data+ '响应拦截');
return data;
}, function(err){
// 对响应错误做点什么
console.log(err)
})
axios.get('http://localhost:3000/adata')
.then(function(data){
console.log(data);
})
异步函数async/await
概述与基本用法
async/await
概述
async function queryDate(id){
const ret = await axios.get('/data');
return ret;
}
queryData.then(ret=>{
console.log(ret);
})
async/await
基本用法
-
await
关键字只能在使用async
定义的函数中使用
axios.defaults.baseURL = 'http://localhost:3000';
/*
async function queryData(){
const ret = await axios.get('adata');
return ret.data;
}
*/
async function queryData(){
var ret = await new Promise(function(resolve, reject){
setTimeout(function(){
resolve('Hello');
},2000)
});
return ret;
}
queryData().then(function(data){
console.log(data);
})
async/await
处理多个异步请求
// 多次异步调用
axios.defaults.baseURL = 'http://localhost:3000';
async function queryData(){
var info = await axios.get('async1');
var ret = await axios.get('async2?info='+ info.data);
return ret.data;
}
queryData().then(function(data){
console.log(data);
})
// 后台路由代码
app.get('/async1', (req, res) => {
res.send('hello')
})
app.get('/async2', (req, res) => {
if(req.query.info == 'hello') {
res.send('world')
}else{
res.send('error')
}
})
案例:图书管理系统
-
图书相关的操作基于后台接口数据进行操作
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。