json-server :Get a full fake REST API with zero coding in less than 30 seconds (seriously)
Github地址 :json-server
安装
使用npm工具进行安装,当你的电脑没有安装nodejs,要先去下载nodejs,在nodejs当中包含了npm工具。NodeJs 下载地址,
如上图,下载这个文件,下载完成之后双击进行安装,安装完成之后,在cmd当中进行验证。使用node -v 和 npm -v
之后进行安装json-server,使用命令 npm install -g json-server
之后使用json-server
检验是否安装成功
添加一个db.json
文件
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
在这个文件的目录下使用cmd输入命令json-server --watch db.json
之后就可以直接进行访问,如 http://localhost:3000/posts?id=1
等api都是可以进行访问的。
Axios测试
在html代码当中进行测试,第一步需要导入axios的包,如下:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
进行测试axios的四种方法,Get 、Post 、Put、Delete
在前面我们先启动localhost3000端口。先定义四个按钮,每个按钮再定义一个单击事件。
<button onclick="Get()">get</button>
<button onclick="Post()">post</button>
<button onclick="Put()">put</button>
<button onclick="Delete()">post</button>
之后在script当中进行方法编写,使用axuis点方法名进行获取数据,
function Get() {
axios.get('http://localhost:3000/posts').then(function(response) {
console.log('get', response.data)
})
}
function Post() {
axios.post('http://localhost:3000/posts', {
"title": "java-axios",
"author": "html-axios"
}).then(function(response) {
console.log('post ', response.data)
})
}
function Put() {
axios.put('http://localhost:3000/posts/2', {
"title": "java-axios-put",
"author": "html-axios-put"
}).then(function(response) {
console.log(response.data)
})
}
function Delete(){
axios.delete('http://localhost:3000/posts/2').then(function (response){
console.log('delete',response.data)
})
}
在浏览器当中查看,就是对db.json这个文件进行操作,增删改查操作,get查、post增、put改、delete删。