axios笔记
1. HTTP回顾
1.1 请求/响应体内容类型
1.2 post请求体参数格式
1.3 API的分类
2. json-serve搭建rest接口
2.1 json-server(github上)
step1:
npm install -g json-server
step2
生成db.json
step3
json-server --watch db.json
3. 使用axios请求rest接口
- step1
BootCDN, 引入在线axios - step2 (get, post)
- step3 (put,delete)
/(ㄒoㄒ)/~~,,是axios.put,写错了我丢
指明删除哪一个
4. XHR(XMLHttpRequest)的理解和使用
4.1 ajax请求与一般的http请求的区别
ajax只是发送请求,拿到数据,但是不会自动刷新,需要我们写代码去更新
4.2 XML请求的API
5. ajax封装(简单版axios)
axios有以下特点,所以如果自己封装的话,就是自己封装的函数要能够实现以下需求
5.1 ajax实现简易axios源码
<body>
<div>
<button onclick="testGet()">GET请求</button>
<button onclick="testPost()">POST请求</button>
<button onclick="testPut()">Put请求</button>
<button onclick="testDelete()">Delete请求</button>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.9.0/axios.min.js"></script>
<script>
//由于在封装axios的时候,返回的是一个promise,所以可以.then
//发送GET请求
function testGet() {
axios({
url: 'http://localhost:3000/posts',
method: 'GET',
params: {
id: 2
}
}).then(
response => {
console.log(response)
},
error => {
alert(error.message)
}
)
}
//发送PUT请求:更新数据,幂等
function testPut() {
axios({
url: 'http://localhost:3000/posts/2',
method: 'put',
data: {
"title": "json-server-put",
"author": "xiong-yang-yang"
}
}).then(
response => {
console.log(response)
},
error => {
alert(error.message)
}
)
}
//发送Delete请求:删除数据,幂等
//delete既可以传query参数,也可以传请求体参数
function testDelete() {
axios({
url: 'http://localhost:3000/posts/2',
method: 'delete',
}).then(
response => {
console.log(response)
},
error => {
alert(error.message)
}
)
}
</script>
<script>
// 自己去配置ajax请求
function axios({
url,
method = 'GET',//默认是GET请求
params = {},
data = {}
}) {
//返回一个promise对象
return new Promise((resolve, reject) => {
// 处理method
method = method.toUpperCase()
// 如果发送的是GET请求,请求内容是拼接在url里的
/* 假设请求体是这个对象(params),需要拼接成 id=1&xxx=abc
{
id:1,
xxx:'abc'
}
*/
let queryString = ''
Object.keys(params).forEach((key) => {
queryString += `${key}=${params[key]}&`
})
if (queryString) {
//去掉queryString最后的一个&
queryString = queryString.substring(0, queryString.length - 1)
//拼接到url上
url += '?' + queryString
}
// 1.执行异步ajax请求
// 1.1创建xhr对象
const request = new XMLHttpRequest()
// 1.2打开连接(初始化请求,没有请求)
request.open(method, url, true)//true代表异步请求
// 1.3发送请求
if (method === 'GET' || method === 'DELETE') {
request.send()
} else if (method === 'POST' || method === 'PUT') {
//告诉服务器请求体的格式是json
request.setRequestHeader('Content-Type', 'application/json;charset=utf-8')
request.send(JSON.stringify(data))//发送json格式请求体参数
}
//绑定状态改变的监听,这是一个同步的任务,放在异步请求前后都可以
request.onreadystatechange = function () {
//如果请求没有完成,直接结束
if (request.readyState !== 4) {
return
}
//如果响应状态码在[200,300)之间代表成功,否者失败
const { status, statusText } = request
//如果请求成功,调用resolve()
if (status >= 200 && status < 300) {
//准备结果数据对象response
const response = {
data: JSON.parse(request.response),
status,
statusText
}
resolve(response)
} else {
reject(new Error('request error status is' + status))
}
}
})
}
</script>
</body>
6. axios
6.1 axios特点
6.2 axios常用语法
- axios.all(promises)—都成功了才成功
6.3 axios基础使用
<body>
<div>
<button onclick="testGet()">GET请求</button>
<button onclick="testPost()">POST请求</button>
<button onclick="testPut()">Put请求</button>
<button onclick="testDelete()">Delete请求</button>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.9.0/axios.min.js"></script>
<script>
//指定默认路径
axios.defaults.baseURL = 'http://localhost:3000'
// GET请求
function testGet() {
axios({
url: '/posts',
params: {
id: 3
}
}).then((response) => {
console.log('/posts get', response.data)
})
}
// POST请求
function testPost() {
// axios.post('/posts', { "title": "json-post", "author": "xiongyangyang" })
axios({
url: '/posts',
method: 'post',
data: {
title: "json-post-new",
author: "xiongyangyang"
}
}).then((response) => {
console.log('/posts post', response.data)
})
}
</script>
</body>
6.4 axios create
6.4.1 为什么用create
6.5 axios拦截器
代码可以在github上找
- request interceptor 后添加先执行
- response interceptor 先添加先执行
// Add a request interceptor 请求拦截器
axios.interceptors.request.use(function (config) {
return config; //有多个请求拦截器时,需要将config return出去,不停的往下传递
}, function (error) {
return Promise.reject(error);
});
// Add a response interceptor 响应拦截器
axios.interceptors.response.use(function (response) {
return response; //不return response的话,response往下传的时候,就变成undefined了,在最后的响应里面,response就变成undefined啦,取不到数据了
}, function (error) {
return Promise.reject(error);
});
6.6 取消请求
6.6.1 取消请求情景一
let cancel // 用于保存取消请求的函数
function getProduct1() {
axios({
url: 'http://localhost:3000',
cancelToken: new axios.CancelToken((c) => { // c是用于取消当前请求的函数
// 保存取消函数,用于之后可能需要取消当前请求
cancel = c;
})
}).then(
response => {
cancel = null //请求有结果了,就不需要cancel了
console.log('请求1成功了', response.data)
},
error => {
cancel = null
console.log(error.message)
}
)
}
function cancelReq() {
//执行取消请求
if (typeof cancel === 'function') {
cancel('强制取消请求')
} else {
console.log('没有可取消的请求')
}
}
6.6.2 取消请求情景二
(发送请求二时,请求一没有请求完,就先取消请求一)
发送多个请求时,有重复的操作,所以需要使用拦截器进行拦截