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

本文详细介绍了Promise的用法,包括resolve/reject、then/catch,并展示了如何封装接口调用,如fetch的简单请求和配置,axios的异步操作和参数传递,以及async/await带来的优雅编程体验。同时涵盖了并发处理、错误捕获和常见API的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Promise用法

接口调用 fetch 用法

接口调用 axios 用法

接口调用 async/await 用法

一 Promise用法

Promise

resolve成功状态

reject拒绝状态

then是前面返回promise的处理

Promise的相关概念

es6新语法 用来处理异步编程

promise是一个对象 可以获取异步操作的消息

好处:

可以避免多层异步调用嵌套的问题(回调地狱)

提供了简洁的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)

实例方法

.then() 得到异步任务的正确结果

.catch() 得到异常信息

.finally() 成功与否都会执行

对象方法

Promise.all() 并发处理多个异步任务 所有任务都执行完成才能得到结果

Promise.race() 并发处理多个异步任务 只要有一个任务完成就能得到结果

二 接口调用 fetch 用法

基本特性

更加简单的数据获取方式 功能更强大 更灵活 可以看做是xhr的升级版

基于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客户端

基本特性:

支持浏览器和node

支持promise

能拦截请求和响应

自动转换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方式传递参数 参考fetch的delete方法

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)

})

实际项目中的应用场景

413259e2838a2a381d5191c16fafc6dd.png

处理多个异步请求

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)

})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值