我们在构建应用时需要访问一个 API 并展示其数据。做这件事的方法有好几种,而使用基于 Promise 的 HTTP 客户端 axios 则是其中非常流行的一种。
现在我们结合json-server来测试
json-server :https://www.cnblogs.com/makalochen/p/13835426.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>axios</title>
</head>
<body>
</body>
<!--直接使用github上面提供的CDN-->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 获取tb1全部数据
axios.get('http://localhost:3000/tb1')
.then((data)=>{
console.log(data);
});
// 获取tb1的id为1一条数据
axios.get('http://localhost:3000/tb1/1')
.then((data)=>{
console.log(data);
})
// 添加一条数据到tb1
axios.post('http://localhost:3000/tb1',{stat:false,title:'喝水'})
.then((d)=>{
console.log(d);
}).catch(error => console.log(error))
// 删除一条数据
axios.delete('http://localhost:3000/tb2/1')
.then((d)=>{
console.log(d);
}).catch(error => console.log(error))
// 修改一条数据
axios.put('http://localhost:3000/tb1/1',{title:'修改后的标题'})
.then((d)=>{
console.log(d);
}).catch(error => console.log(error))
</script>
</html>