axios的核心原理以及封装axios
HTTP请求API分类:REST API与非RES TAPI使用json-server
·
axios的特点
0.是基于promise的异步ajax请求库
1.浏览器端/node端都可以使用
2.即可以发送http普通请求,也可以发送异步请求
3.可以拦截请求(请求拦截和响应拦截做统一的处理)
4.可以取消中断请求
5.请求/响应数据的转换(比如使用post请求更新服务端数据,那么你data中传的是json对象,而有些服务器不支持接收json格式的数据,那么奴可以再axios请求中先将数据转成字符串的形式—JSON.stringify(data),或者响应的时候,将响应数据转换为我们想要的json格式的数据(JSON.pars(data)
6.可以批量发送多个请求(使用axios.create()比如不是只想一个服务器发送请求,可以指定服务器)
HTTP请求
API分类:REST API与非RES TAPI
使用json-server
封装axios函数(发送异步请求)
xhr.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="getRequest()">发送GET请求</button>
<button onclick="postRequest()">发送POST请求</button>
<script>
//get请求
function getRequest() {
axios({
url: 'http://localhost:3000/posts',
method: 'GET',
params: {
id: 1,
name: 'hhhh'
}
}
).then(
response => {
console.log(response)
},
error => {
alert(error.msg)
}
)
}
//POST请求,向服务器保存数据
function postRequest() {
axios({
url: 'http://localhost:3000/posts',
method: 'POST',
data: {
"title": "json-server---",
"author": "typicode---"
}
}
).then(
response => {
console.log(response)
},
error => {
alert(error.msg)
}
)
}
//封装ajax请求,
function axios({ url, method = 'GET', params = {}, data = {} }) {
//由于参数的影响,因此需要对url进行处理(即是url与参数params的关系拼接处理
let queryParams = ''
Object.keys(params).forEach(key => {
queryParams += `${key}=${params[key]}&`//因为可能为多个key
})
if (queryParams) {//当queryParams不为空时候表示冰洁完成,去掉后面重复的$
queryParams = queryParams.substring(0, queryParams.length - 1)
url = '?' + queryParams
}
//返回的时Promise对象
return new Peomise((resolve, reject) => {
//1.创建xhr对象(XMLHttpRequest)
const xhr = new XMLHttpRequest();
//2.打开连接(初始化请求,此时并没有发出请求)
xhr.open(method, url, true);//这里的true表示发送异步请求,也是.open中的默认值
//3.发送请求
if (method === 'GET') {
xhr.send(null);
} else if (method == 'POST') {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8')
xhr.send(JSON.stringify(data));//此时携带的参数是jaon格式,那么在上面必须设置请求头,告诉服务器请求参数为json格式
}
//绑定状态改变的更新(由于请求是异步的,而下面的监听是同步的,放在下面也可以得到监听的效果)
xhr.onreadystatechange = function () {
//如果请求还没有完成,直接结束
if (xhr.readyState !== 4) {
return
}
//如果响应码在【200,300】之间代表成功,否则失败
const { status, statusText } = xhr;
//成功
if (status > 200 && status < 300) {
//此时代表请求成功,那么响应的请求得到的数据会在xhr中,可以通过回调函数的形式获取
//响应数据可以参看github文档
const response = {//这里使用结构解析的方式获取想要的相应数据
data: JSON.parse(xhr.data),//返回的是字符串形式,要转换为json格式
status,
statusText
}
resolve(response);
} else {
//请求失败
reject(new Error('request is error' + status))
}
}
})
}
</script>
</body>
</html>
根目录下的db.json文件(要下载json-server,会默认开启端口为3000的服务器)
{
"posts": [
{
"title": "json-server+++",
"author": "typicode+++",
"id": 1
},
{
"id": 3
},
{
"title": "json-server3",
"author": "typicode3",
"id": 6
},
{
"title": "json-server4",
"author": "typicode4",
"id": 7
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}
可请求:
1.http://localhost:3000/posts'
2.http://localhost:3000/comments'
3.http://localhost:3000/profile'
解析:
比如使用Promise对象.then中得到的响应数据
更多推荐
已为社区贡献1条内容
所有评论(0)