手动实现一个简单的 axios 增删改查的功能封装,实现非 rest API 接口的数据请求,数据的模拟用 json-server 来实现
预备数据
首先,全局安装 json-server
npm install -g json-server
在本地建立 db.json 文,并填充数据
{
"posts": [
{"id": 1, "title": "json-server", "author": "typicode"},
{"id": 2, "title": "json-server2", "author": "typicode2"},
{"title": "json-server+++", "author": "typicode+++", "id": 3}
],
"comments": [
{"id": 1, "body": "some comment", "postId": 1}
],
"profile": {
"name": "typicode"
}
}
实现原理
html 代码
<div>
<button onclick="testGet()">xhr发送GET请求</button>
<button onclick="testPost()">xhr发送请POST求</button>
<button onclick="testPut()">xhr发送PUT请求</button>
<button onclick="testDelete()">xhr发送DELETE请求</button>
</div>
js 代码
// 引入 xios
<script