文章目录
1.使用json-server搭建一个REST的api(接口)
复习:REST的api
由请求方式来决定进行增删改查(CRUD)的哪个操作
同一个请求路径可以进行多个操作
请求方式用到GET/POST/PUT/DELETE
下载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
,可以在localhost:3000中访问到data数据,
并拥有三个REST接口:localhost:3000/posts
,localhost:3000/comments
和localhost:3000/profile
2.使用axios的GET/POST/PUT/DELETE分别请求上述REST接口
<button class="getbtn">get请求</button>
<button onclick="postbtn()">post请求</button>
<button onclick="putbtn()">put请求</button>
<button class="delbtn">delete请求</button>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios.defaults.baseURL = "http://localhost:3000";
// 1.GET请求:获取posts接口中的数据==>查
var getbtn = document.querySelector(".getbtn");
getbtn.addEventListener("click", function() {
//此处/1是获取posts接口中id:1的对象
// axios.get('http://localhost:3000/posts/1')
//?id=1的效果同上
axios.get('/posts?id=1')
.then(response => {
console.log("get请求获取/posts接口中的数据:", response.data);
})
});
// 2.POST请求:向comments接口传参(添加数据)并返回接口中的数据==>增
function postbtn() {
// axios.post("http://localhost:3000/comments", {
// id: 2,
// body: "post body",
// postId: 2
// })
// .then(res => {
// console.log("我是comments接口中的数据:", res.data);
// })
// .catch(res => {
// console.log("我是失败的数据:", res);
// })
/*注意post方法添加数据只能提交一次,重复提交会报错:500(服务器出错)
此处用了不同的接口提交就是为了验证上述结论*/
axios.post("/posts", {
id: 2,
body: "post body",
postId: 2
})
.then(res => {
console.log("我是comments接口中的数据:", res.data);
})
.catch(res => {
console.log("我是失败的数据:", res);
})
}
// 3.使用put请求:修改posts接口中的数据==>改
const putbtn = () => {
axios.put('http://localhost:3000/posts/1', { //这个1会修改posts有id:1属性的对象中的数据
title: 'czh...',
author: 'czh...'
})
.then((response) => {
console.log('我是put请求的数据:', response.data)
})
}
// 4.发送delete请求:删除posts中id:2的数据==>删
var delbtn = document.querySelector(".delbtn");
delbtn.addEventListener("click", function() {
console.log("hello....");
axios({
method: "DELETE",
url: "/posts/3"
})
.then(res => {
console.log("我是delete请求的数据:", res.data);
//获取不到结果,因为当前路径是http://localhost:3000/posts/2不是http://localhost:3000/posts
})
});
</script>
结果:
最终的db.json内容为
{
"posts": [
{
"title": "czh...",
"author": "czh...",
"id": 1
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
},
{
"id": 2,
"body": "post body"
}
],
"profile": {
"name": "typicode"
}
}