json-server 搭建REST接口 和Axios方法简单测试

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删。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Modify_QmQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值