前后端交互模式
1.接口调用方式
原生ajax
基于jQuery的ajax
fetch
axios
2.URL
(1)传统的URL
协议://域名或IP地址:端口号/路径?参数#锚点
(2)Restful形式的URL
HTTP请求方式:
get 查询
post 添加
put 修改
delete 删除
Promise
一、概述
Promise是异步编程的一种解决方案,
从语法上讲,Promise是一个对象,从它可以获取异步操作的消息。
二、使用Promise的好处
可以避免回调地狱(多层异步调用嵌套问题)
Promise对象提供了简洁的API,使得控制异步操作更容易
三、基本用法
- 实例化Promise对象,在构造函数中传递函数,该函数用于处理异步任务
- resolve和reject两个参数用于处理成功和失败的两种情况,并通过p.then获取处理结果
//1
var p = new Promise(function(resolve,reject){
//成功时调用resolve()
//失败时调用reject()
})
//2
p.then(function(ret){
//从resolve得到正常结果
},function(ret){
//从reject得到错误信息
})
实例:
(1)基于Promise发送Ajax请求
//基于Promise发送Ajax请求
//1
function queryData(url){
var p = new Promise(function(resolve,reject){
//发送Ajax异步请求
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()
})
return p;
}
//2
queryData('http://localhost/data')
.then(function(ret){
console.log(ret)
}, function(ret){
console.log(ret)
})
(2)发送多个Ajax请求,并保证顺序
//发送多个Ajax请求,并保证顺序
queryData('http://localhost/data')
.then(function(ret){
console.log(ret)
return queryData('http://localhost/data2')
})
.then(function(ret){
console.log(ret)
return queryData('http://localhost/data3')
})
.then(function(ret){
console.log(ret)
})
四、then参数中的函数返回值
1.返回Promise实例对象
返回的该实例对象会调用下一个then
2.返回普通值
返回的普通值会直接传递给下一个then,通过then参数中函数的参数接受该值
五、Promise的常用API—实例方法
p.then() 得到异步任务的正确结果
p.catch() 获取异常信息
p.finally() 成功与否都会执行(尚且不是正式标准)
queryData('http://localhost/data')
.then(function(){})
.catch(function(){})
.finally(function(){})
六、Promise的常用API—对象方法
Promise.all() 并发处理多个异步任务,所有任务都执行完才能得到结果
Promise.race() 并发处理多个异步任务,只要有一个任务执行完就能得到结果
var p1 = queryData('http://localhost/data')
var p2 = queryData('http://localhost/data2')
var p3 = queryData('http://localhost/data3')
//
Promise.all([p1,p2,p3])
.then(function(result){
console.log(result)
})
//
Promise.race([p1,p2,p3])
.then(function(result){
console.log(result)
})
//
fetch调用接口
一、基本用法
fetch(url)
.then(data => {
//固定写法
return data.text()
})
.then(ret => {
//这里得到的才是最终的数据
console.log(ret)
})
二、fetch请求参数
(1)常用配置选项
method(string): HTTP请求方法,默认为GET (GET, POST, PUT, DELETE)
body(string): HTTP请求参数
headers(Object): HTTP的请求头
(2)GET请求方式的参数传递
fetch(http://localhost/data?id=3, {method: 'get'})
.then(function(data){
return data.text()
})
.then(function(ret){
console.log(ret)
})
(3)DELETE请求方式的参数传递
与GET相似
fetch('http://localhost/data/3', {method: 'delete'})
.then(function(data){
return data.text()
})
.then(function(ret){
console.log(ret)
})
(4)POST请求方式的参数传递
参数为字符串格式:
fetch('http://localhost/data', {
method: 'post',
body: 'uname=lisi&pwd=123456',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(data){
return data.text()
})
.then(function(ret){
console.log(ret)
})
参数为json格式 (通过JSON.stringify方法转为字符串格式):
fetch('http://localhost/data', {
method: 'post',
body: JSON.stringify({uname:'lisi', age:18}),
headers: {'Content-Type': 'application/json'}
})
.then(function(data){
return data.text()
})
.then(function(ret){
console.log(ret)
})
(5)PUT请求方式的参数传递
与POST相似
fetch('http://localhost/data/123', {
method: 'put',
body: JSON.stringify({uname:'lisi', age:18}),
headers: {'Content-Type': 'application/json'}
})
.then(function(data){
return data.text()
})
.then(function(ret){
console.log(ret)
})
(6)fetch响应数据格式
text() 将返回体处理成字符串类型
json() 返回结果和JSON.parse(responseText) 一样
fetch('http:localhost/data')
.then(function(data){
//return data.text()
return data.json()
})
.then(function(ret){
//console.log(ret)
console.log(ret.uname)
console.log(ret.age)
})
axios调用接口
一、基本特性
支持浏览器和node.js
支持Promise
能拦截请求和响应
自动转换JSON数据
二、基本用法
axios.get('/login')
.then(function(ret){
//data属性名称是固定的,用于获取后台响应数据
console.log(ret.data)
})
三、axios的常用API
get: 查询数据
post: 添加数据
put: 修改数据
delete: 删除数据
四、axios的参数传递
(1)GET传递参数
可以通过url传递参数;
也可以通过params选项传递参数。
//方式一:通过url传递参数
axios.get('login?id=123')
.then(ret => {
console.log(ret.data)
})
//方式二:通过params选项传递参数
axios.get('/login', {params:{id:123}})
.then(ret => {
console.log(ret.data)
})
(2)DELETE传递参数
与GET相似
(3)POST传递参数
可以通过选项传递参数 (默认传递的是json格式的数据);
也可以通过URLSearchParams传递参数 (application/x-www-form-urlencoded)
//方式一:通过选项传递参数
axios.post('/login', {uname:'tom', pwd:123})
.then(ret => {
console.log(ret.data)
})
//方式二:通过URLSearchParams传递参数
const params = new URLSearchParams()
params.append('uname': 'lisi')
params.append('pwd': '123456')
axios.post('/login', params)
.then(ret => {
console.log(ret.data)
})
(4)PUT传递参数
与POST相似
五、axios响应结果
响应结果的主要属性:
data: 实际响应回来的数据
headers: 响应头信息
status: 响应状态码
statusText: 响应状态信息
六、axios的全局配置
axios.defaults.timeout=3000 超时时间
axios.defaults.baseURL=“http://localhost:3000/app” 默认地址
axios.defaults.headers[‘token’]=“wqjff” 设置请求头
//配置请求的基准url地址
axios.defaults.baseURL= 'http://localhost:3030/'
//
axios.get('login')
.then(ret => {
console.log(ret.data)
})
七、axios请求拦截器
在请求发出之前设置一些信息
//axios.interceptors.request.use(function(){}, function(){})
axios.interceptors.request.use(function(config){
//在请求之前进行一些信息设置
return config
}, function(err){
//处理响应的错误信息
console.log(err)
})
八、axios响应拦截器
在获取数据之前对数据做一些加工处理
axios.interceptors.response.use(function(res){
return res
}, function(err){
console.log(err)
})
async/await
async关键字用于函数上,async的函数返回值是Promise实例对象
await关键字用于async函数当中,await可以得到异步的结果
async function queryData(id){
const ret = await axios.get('/user')
return ret.data
}
queryData.then(data => {
console.log(data)
})