1.axios的安装:
使用npm
$ npm install axios
使用yarn
yarn add axios
使用 jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
因为我们国内的映像什么的如果用国外的,那么肯定网速会非常差,所以可以在bootcdn上搜索axios,取得国内的最快映像
2.axios创建虚拟服务器
首先要先创建一个json-server的虚拟服务器
步骤如下:
先全局安装json-server环境
npm install -g json-server
然后创建一个db.json文件,输入以下代码
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
再以以下方式开启服务
json-server --watch db.json
3.axios基本案例:简单的get、post、put、delete请求
<!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>Document</title>
</head>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.2/css/bootstrap-grid.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.2/axios.min.js"></script>
<body>
<div class="container">
<h2 class="page-header">axioss基本使用</h2>
<button class="btn btn-primary">发送get请求</button>
<button class="btn btn-warning">发送post请求</button>
<button class="btn btn-succes">发送put请求</button>
<button class="btn btn-danger">发送delete请求</button>
</div>
<script>
const btn=document.querySelectorAll("button")
btn[0].onclick=function(){
axios({
methods:'GET',
url:'http://localhost:3000/post/2'
}).then(response=>{
console.log(response);
})
}
btn[1].onclick=function(){
axios({
methods:'POST',
url:'http://localhost:3000/post',
// 在这里表示将数据传入到post文件夹下面当中
// 设置请求体
data:{
title:"laozhichi love liulijuan",
author:"laozhichi"
}
}).then(response=>{
console.log(response);
})
}
btn[2].onclick=function(){
axios({
methods:'POST',
url:'http://localhost:3000/post/3',
// 在这里表示将数据x传入并修改post下面的3这个位置的数据
// 设置请求体
data:{
title:"laozhichi love liulijuan",
author:"laozhichi"
}
}).then(response=>{
console.log(response);
})
}
btn[3].onclick=function(){
axios({
methods:'POST',
url:'http://localhost:3000/post/3',
// 在这里表示删除post下的第三个信息
// 设置请求体
}).then(response=>{
console.log(response);
})
}
</script>
</body>
</html>