第四周学习内容整理
前后端交互
1、前后端调用模式
- 接口调用方式
~~~ 原生ajax
~~~ 基于jQuery的ajax
~~~ fetch
~~~ axios - 传统形式的URL
格式:schema://host:post/path?query#fragment
~~
schema:协议。例如http、https、ftp等
~~
host:域名或者IP地址
~~
port:端口,http默认端口80,可以省略
~~
path:路径,例如/abc/a/b/c
~~
query:查询数据,例如uname=lisi&age=12
~~
fragment:锚点(哈希Hash),用于定位页面的某个位置
符合规则的URL
http://www.itcast.cn
http://www.itcast.cn/java/web
http://www.itcast.cn/java/web?flag=1
http://www.itcast.cn/java/web?flag=1#function
- Restful形式的URL
HTTP请求方式
~~
GET
~~
查询
~~
POST
~~
添加
~~
PUT
~~
修改
~~
DELETE
~~
删减
符合规则的URL地址
http://www.hello.cim/books
~~
GET
http://www.hello.cim/books
~~
POST
http://www.hello.cim/books/123
~~
PUT
http://www.hello.cim/books/123
~~
DELETE
2、promise用法
- 异步调用
异步效果分析
~~~ 定时任何
~~~ ajax
~~~ 事件函数
多次异步调用的依赖分析
~~~ 多次异步调用的结果顺序不确定
~~~ 异步调用结果如果不存在依赖需要嵌套 - Promise概述
Promise是异步编程的一种解决方案,从语法上讲,Promise是一个对象,从它可以获取异步操作的消息。
好处:
~~~ 可以避免多层异步调用嵌套问题(回调地狱)
~~~ promise 提供了简洁的API,使得控制异步操作更加容易
官网:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise - Promise基本用法
~~~ 实例化Promise对象,构造函数中传递函数,该函数中用于处理异步任务
~~~ resolve和rejrct两个参数用于处理成功和失败两种情况,并通过p.then获取处理结果
var p = new Promise(function(resolve, reject){
//成功时调用 resolve()
//失败时调用 reject()
});
p.then(function(ret){
//从resolve得到正常结果
},function(ret){
//从reject得到错误信息
});
- 基于Promise处理Ajax请求
处理原生Ajax
function queryData() {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState != 4) return;
if(xhr.status == 200) {
resolve(xhr.responseText);
}else{
reject('出错了');
}
}
xhr.open('get','/data');
xhr.send(null);
})
}
发送多次ajax请求
queryData()
.then(function(data){
return queryData();
})
.then(function(data){
return queryData();
})
.then(function(data){
return queryData();
});
- Promise常用API
实例方法
~~~ p.then() 得到异步任务的正确结果
~~~ p.catch() 获取异常信息
~~~ p.finally()成功与否都会执行(尚且不是正式标准)
queryData()
.then(function(data){
console.log(data);
})
.catch(function(data){
console.log(data);
})
.finally(function(data){
console.log('finished');
});
对象方法
Promise.all() 并发处理多个异步任务,所有任务都执行完成才能得到结果
Promise.race() 并发处理多个异步任务,只要有一个任务完成就能得到结果
Promise.all([p1,p2,p3]).then((result) => {
console.log(result)
})
Promise.race([p1,p2,p3]).then((result) => {
console.log(result)
})
3、fenth
- 基本特性
更加简单的数据获取方式,功能更强大,更灵活,可以看作是xhr的升级版
基于Promise实现
官网:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API - 语法结构
fetch(url).then(fn2)
.then(fn3)
...
.catch(fn)
fetch('/abc').then(data=>){
return data.text();
}).then(ret=>{
//注意这里得到的才是最终数据
console.log(data);
});
- fetch请求参数
常用配置选项
~~~ method(String):HTTP请求方法,默认GET(GET、POST、PUT、DELETE)
~~~ body(String):HTTP的请求参数
~~~ headers(Object):HTTP的请求头,默认为{}
fetch('/abc', {
method: 'get'
}).then(data=>){
return data.text();
}).then(ret=>{
//注意这里得到的才是最终数据
console.log(ret);
});
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);
});
DELETE请求方式的参数传递
fetch('/abc/123', {
method: 'delete'
}).then(data=>){
return data.text();
}).then(ret=>{
//注意这里得到的才是最终数据
console.log(ret);
});
POST请求方式的参数传递
fetch('books', {
method: 'post',
body: 'uname=lisi&pwd=123',
headers: {
'content-Type': 'application/x-www-form-urlencoded',
}
}).then(data=>){
return data.text();
}).then(ret=>{
console.log(ret);
});
fetch('/books', {
method: 'post',
body: JSON.stringify({
uname: 'lisi',
age: 12
})
headers: {
'Content-Type': 'application/json' ,
}
}).then(data=>){
return data.text();
}).then(ret=>{
console.log(ret);
});
- fetch响应式结果
响应数据格式
~~~ text():将返回体处理成字符串类型
~~~ ison():返回结果和JSON。parse(responesText)一样
fetch('/abc') then(data=>){
// return data.text();
return data.json();
}).then(ret=>{
console.log(ret);
});
4、axios用法
- axios基本特性
是一个基于Promise用于浏览器和node.js的HTTP客户端
官网https://github.com/axios/axios
特征
~~~ 支持浏览器和node.js
~~~ 支持promise
~~~ 能拦截请求和响应
~~~ 自动转换JSON数据 - axios基本用法
axios.get('/adata')
.then(ret=>){
// data属性是固定的用法,用于获取后台响应的数据
console.log(ret.data)
})
- axios常用API
~~~ get:查询数据
~~~ post:添加数据
~~~ put:修改数据
~~~ delete:删除数据 - axios的参数传递
(1)GET传递参数
通过URL传递参数
通过params 选项传递参数
axios.get('/adata?id=123')
.then(ret=>){
console.log(ret.data)
})
axios.get('/adata/123')
.then(ret=>){
console.log(ret.data)
})
axios.get('/adata', {
params: {
id: 123
}
})
.then(ret=>){
console.log(ret.data)
})
(2)DELETE传递参数
参数传递与GET相似
axios.delete('/adata?id=123')
.then(ret=>){
console.log(ret.data)
})
axios.delete('/adata/123')
.then(ret=>){
console.log(ret.data)
})
axios.delete('/adata', {
params: {
id: 123
}
})
.then(ret=>){
console.log(ret.data)
})
(3)POST传递参数
通过选项传递参数(默认json格式数据)
axios.post('/adata', {
uname: 'tom',
pwd: 123
}) .then(ret=>){
console.log(ret.data)
})
通过URLSearchParams传递参数(application/x-www-form-urlencoded)
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/api/test', params).then(ret=>){
console.log(ret.data)
})
(4)PUT传递参数
axios.put('/adata/123', {
uname: 'item',
pwd: 123
}) .then(ret=>){
console.log(ret.data)
})
- axios的响应结果
响应结果的主要属性
~~~ data:实际响应回来的数据
~~~ headers:响应头信息
~~~ status:响应状态码
~~~ statusText:响应状态信息
axios.post('/axios-json').then(ret=>){
console.log(ret)
})
- axios的全局配置
~~~ axios.defaults.timeout = 3000;//超时时间
~~~ axios.defaults.baseURL = ‘https://localhost:3000/app’;//默认地址
~~~ axios.defaults.headers.[‘mytoken’] = ‘aqwerwwqwer2ewrwe23eresdf23’;//设置请求头 - axios拦截器
(1)请求拦截器
在请求发出之前设置一些信息
//添加一个请求拦截器
axios.interceptors.request.use(function(config) {
//在请求发出之前进行一些信息设置
return config;
}, function(err){
//处理响应的错误消息
});
(2)响应拦截器
在获取数据之前对数据做一些加工处理
//添加一个响应拦截器
axios.interceptors.request.use(function(res) {
//在这里对返回的数据进行处理
return res;
}, function(err){
//处理响应的错误消息
});
5、async/await的基本用法
~~~
async/await是ES7引入的新语法,可以更加方便的使用异步操作
~~~
async关键字用于函数上(async函数返回值是Promise实例对象)
~~~
await关键字用于async函数当中(await可以得到异步的结果)
async function queryData(id) {
const.ret = await axios.get('/data');
return ret;
}
queryData(ret=>){
console.log(ret)
})
async/await处理多个异步请求
多个异步请求的场景
async function queryData(id) {
const info = await axios.get('async1');
const ret = await axios.get('async2?info=' + info.data);
return ret;
}
queryData(ret=>){
console.log(ret)
})