本文为我学习axios的笔记。
前置知识:
axios是什么
axios是目前前端最流行的ajax请求库,vue和react都推荐使用axios发送ajax请求。
axios特征
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
json-server安装
https://github.com/typicode/json-server
启动命令
$ json-server --watch db.json
如果要延时,加上-d和时间(单位:ms)
$ json-server --watch db.json -d 2000
然后就可以愉快地访问http://localhost:3000了
具体操作还是见https://github.com/typicode/json-server
还有一个很好的网站叫做jsonplaceholder,可以用来辅助学习axios,推荐大家感兴趣的可以看看
https://jsonplaceholder.typicode.com/
axios安装
https://github.com/axios/axios
axios使用
axios外链接配置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>axios配置</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
</head>
<body>
<script>
console.log(axios);
</script>
</body>
axios基本使用
<body>
<div class="container">
<button>发送 GET 请求</button>
<button>发送 POST 请求</button>
<button>发送 PUT 请求</button>
<button>发送 DELETE 请求</button>
</div>
<script>
const btns = document.getElementsByTagName('button');
btns[0].onclick = function () {
axios({
method: 'GET',
url: 'http://localhost:3000/posts/1'
}).then(res => {
console.log(res);
})
}
btns[1].onclick = function () {
axios({
method: 'POST',
url: 'http://localhost:3000/posts',
data: {
title: '馍馍汉宝',
author: 'qg'
}
}).then(res => {
console.log(res);
})
}
btns[2].onclick = function () {
axios({
method: 'PUT',
url: 'http://localhost:3000/posts/2',
data: {
title: '馍馍汉宝',
author: 'xg'
}
}).then(res => {
console.log(res);
})
}
btns[3].onclick = function () {
axios({
method: 'DELETE',
url: 'http://localhost:3000/posts/2',
}).then(res => {
console.log(res);
})
}
</script>
</body>
axios的其他使用
<body>
<div class="container">
<button>发送 GET 请求</button>
<button>发送 POST 请求</button>
<button>发送 PUT 请求</button>
<button>发送 DELETE 请求</button>
</div>
<script>
const btns = document.getElementsByTagName('button');
btns[0].onclick = function () {
axios.request({
method: 'GET',
url: 'http://localhost:3000/posts'
}).then(res => {
console.log(res);
})
}
btns[1].onclick = function () {
axios.post(
'http://localhost:3000/posts',
{
"id": 4,
"title": "hello world",
"author": "hg"
}
).then