基于Promise 接口调用方式 ajax fetch axios async/await 前后端交互

  1. Promise用法
  2. 接口调用 fetch 用法
  3. 接口调用 axios 用法
  4. 接口调用 async/await 用法

一 Promise用法

Promise
resolve成功状态
reject拒绝状态
then是前面返回promise的处理

Promise的相关概念
es6新语法 用来处理异步编程
promise是一个对象 可以获取异步操作的消息
好处:

  1. 可以避免多层异步调用嵌套的问题(回调地狱)
  2. 提供了简洁的API 使得控制异步操作更加容易

基于promise发送ajax请求

// 封装一个独立的函数
function queryData(){
	return pro = new Promise((resolve, reject)=>{
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = () =>{
			if(xhr.readyState != 4) return;
			if(xhr.readyState == 4 && xhr.status == 200){
				// 处理正常的情况
				resolve(xhr.responsetext)
			}else{
				// 处理异常情况
				reject('服务器错误')
			}
		}
		xhr.open('get', url); // 准备发送前的参数
		xhr.send(null);
	});
}
// 单个ajax请求
queryData('http://localhost:3000/data')
	.then((data)=>{
		console.log(data)
	},(info)=>{
		console.log(info)
	})
// 多个ajax请求 并且保证顺序
queryData('http://localhost:3000/data')
	.then((data)=>{
		console.log(data)
		return queryData('http://localhost:3000/data1')
	})
	.then((data)=>{ // 得到上一步的异步任务的结果
		console.log(data)
		return queryData('http://localhost:3000/data2')
	})
	.then((data)=>{
		console.log(data)
	})

then 参数中的函数返回值
返回promise实例对象—返回的该实例对象会调用下一个then
返回普通值—返回的普通值会直接传递给下一个then 通过then参数中函数的参数接收该值

promise常用的API

// 打印promise的详细信息
console.dir(Promise)
  1. 实例方法
    .then() 得到异步任务的正确结果
    .catch() 得到异常信息
    .finally() 成功与否都会执行

  2. 对象方法
    Promise.all() 并发处理多个异步任务 所有任务都执行完成才能得到结果
    Promise.race() 并发处理多个异步任务 只要有一个任务完成就能得到结果

二 接口调用 fetch 用法

基本特性

  1. 更加简单的数据获取方式 功能更强大 更灵活 可以看做是xhr的升级版
  2. 基于promise实现
fetch('http://localhost:3000/data').then(data=>{
	// text()方法属于fetch API的一部分 它返回一个promise实例对象 得到后台返回的数据
	return data.text()
})then(data=>{
	console.log(data)
})

fetch请求参数 常用参数配置
method(String):HTTP 请求方法 默认为 GET(GET,POST,PUT,DELETE)
body(String):HTTP请求参数
headers(Object):HTTP的请求头 默认为{}

GET请求

fetch('http://localhost:3000/data?id=1',{method:'get'}).then(data=>{
	return data.text()
})then(data=>{
	console.log(data)
})

GET后台接口

app.get('/data',(req,res)=>{
	res.send('传统url传递参数' + req.query.id)
})

DELETE 请求

fetch('http://localhost:3000/list/1',{method:'delete'}).then(data=>{
	return data.text()
})then(data=>{
	console.log(data)
})

DELETE后台接口

app.delete('/list/:id',(req,res)=>{
	res.send('restful形式的url传递参数' + req.params.id)
})

POST请求 传统参数

fetch('http://localhost:3000/lists',{
	method:'post',
	body:'uname=lisi&pwd=222',
	headers:{
		'Content-Type':'application/x-www-form-urlencoded'
	}
}).then(data=>{
	return data.text()
})then(data=>{
	console.log(data)
})

POST后台接口

app.post('/lists',(req,res)=>{
	res.send('post请求' + req.body.uname + req.body.pwd)
})
// body是由body-parser中间件提供的

POST请求 json格式

fetch('http://localhost:3000/lists',{
	method:'post',
	body:JSON.stringify({
		uname:'lisi',
		pwd:222
	}),
	headers:{
		'Content-Type':'application/json'
	}
}).then(data=>{
	return data.text()
})then(data=>{
	console.log(data)
})

put请求与post请求类似

fetch响应数据格式
text() 将返回体处理成字符串类型
json() 返回结果和JSON.parse(responseText) 一样
json格式使用将上面的text()换成json()就可以 后台返回的数据格式就应该是json格式

三 接口调用 axios 用法

基于promise用于浏览器和node.js的HTTP客户端
基本特性:

  1. 支持浏览器和node
  2. 支持promise
  3. 能拦截请求和响应
  4. 自动转换JSON数据

先下载 axios

axios.get('http://localhost:3000/data').then(ret=>{
	// data属性是固定的 用于获取后台响应的数据
	console.log(data.ret)
})

后台接口

app.get('/data',(req,res)=>{
	res.send('hello axios')
})

axios常用API
get post put delete

GET传递参数
通过URL传递参数
通过params选项传递参数

axios.get('http://localhost:3000/data?id=1').then(ret=>{
	console.log(data.ret)
})

后台接口

app.get('/data',(req,res)=>{
	res.send('axios get传递参数' + req.query.id)
})

也可以通过restful方式传递参数 参考fetchdelete方法

params传递参数

axios.get('http://localhost:3000/data',{
	params:{ // 可以传递多个参数 比较方便
		id:1
	}
}).then(ret=>{
	console.log(data.ret)
})

后台接口

app.get('/data',(req,res)=>{
	res.send('axios get传递参数' + req.query.id)
})

DELETE传递参数与GET类似

POST传递参数

默认传递的是JSON格式的数据 需要后台提供支持
axios.post('http://localhost:3000/data',{
	uname:'lisi',
	pwd:222
}).then(ret=>{
	console.log(data.ret)
})

后台接口

app.post('/data',(req,res)=>{
	res.send('axios post传递参数' + req.body.uname + req.body.id)
})
// 通过 URLSearchParams 传递参数 
// 如果后台支持json使用上面那种方法 如果两种都支持还是使用上面那种方法
var params = new URLSearchParams();
params.append('uname', 'lisi')
params.append('pwd', '222')
axios.post('http://localhost:3000/data',params).then(ret=>{
	console.log(data.ret)
})

后台接口

app.post('/data',(req,res)=>{
	res.send('axios post传递参数' + req.body.uname + req.body.id)
})

put请求与post请求类似

axios的响应结果
data 实际响应回来的数据
headers 响应头信息
status 响应状态码
statusText 响应状态信息

axios的全局配置

// 超时时间
axios.defaults.timeout = 5000; 
// 配置请求的基准URL地址
axios.defaults.baseurl = 'http://localhost:3000'
// 请求头信息 
axios.defaults.headers['token'] = 'xxxxx'

axios拦截器
请求拦截器 在请求发出之前配置一些信息

// 添加请求拦截器 通过拦截器可以控制所有请求
axios.interceptors.request.use(config=>{
	config.headers.token = 'xxx' // 配置请求头
	return config
},err=>{
	console.log(err)
})

响应拦截器 在获取数据之前对数据做一些加工处理

// 添加响应拦截器 
axios.interceptors.response.request.use(res=>{
	console.log(res)
	return res
},err=>{
	console.log(err)
})

四 接口调用 async/await 用法

async/await 是ES7引入的新语法 可以更加方便的进行异步操作
async关键字同于函数上 async函数的返回值是Promise实例对象
await关键字用于async函数当中 await可以得到异步的结果

async function queryData(id){
	const ret = await.get('xxxx')
	return ret
}
queryData.then(ret=>{
	console.log(ret)
})

实际项目中的应用场景
在这里插入图片描述
处理多个异步请求

async function queryData(id){
	const info = await axios.get('xxxx1')
	const ret = await.get('xxxx2?info=' + info.data)
	return ret.data
}
queryData.then(data=>{
	console.log(data)
})
发布了41 篇原创文章 · 获赞 2 · 访问量 1836

猜你喜欢

转载自blog.csdn.net/weixin_43883485/article/details/105142491
今日推荐