json-server(模拟后端接口请求)

1、下载
	cnpm install -D json-server@0.16.2

2、使用
	(1)创建.json文件添加属性
		localhost:3000/键名	
		localhost:3000/键名/id值返回对应的字段
		
		{
		  "posts": [
		    { "id": 1, "title": "json-server", "author": "typicode" }
		  ],
		  "comments": [
		    { "id": 1, "body": "some comment", "postId": 1 }
		  ],
		  "profile": { "name": "typicode" }
		}
		增加数据:
			使用post方式,localhost:3000/键名,带上请求参数即可增加数据
			或者使用postman,在请求数据的时候带上json数据,使用x-www-form-urlencoded添加数据
		
	(2)开启服务
		json-server -w json文件路径 
			--port 端口名称默认为3000
			--delay 延迟响应毫秒
			
	(3)请求接口,会根据请求返回内容动态修改json文件里的内容
		通过请求方法的不同,模拟对数据的增删改查
		使用postman也是根据请求的字段进行,x-www-form-urlencoded方式进行参数的携带
		
		增加数据post
			axios({
			    method:"post",
			    url:"http://localhost:3000/键名",
			    data:{
			      username:"Yi只猴",
			      age:18
			    }
			  }).then((data)=>{
			    console.log(data)
			  })
		
			
		删除某一条delete
			
			axios({
			   method:'delete',
			   url:'http://localhost:3000/键名/id值'
			 }).then((data)=>{
			   console.log(data)
			 })
		
			
		修改数据
		    修改指定数据patch,没有会添加
			axios({
			    method:"patch",	
			    url:"http://localhost:3000/data/3",//ID
			    data:{
			      username:'嘻嘻' 
			    }
			 }).then((data)=>{
			   console.log(data)
			 })
		   
		   替换所有数据put
		   	axios({
			    method:"put",	
			    url:"http://localhost:3000/data/3",
			    data:{
			      username:'嘻嘻' 	或替换所有内容
			    }
			 }).then((data)=>{
			   console.log(data)
			 })
						  
			
		根据指定字段查找
			axios({
			      method:"get",
			      url:"http://localhost:3000/data?username=小猴",
			  }).then((data)=>{
			     console.log(data)
			  })
  	
  	(4)添加中间件提前处理请求
  		创建.js文件 
  			module.exports=(req,res,next)=>{
  				req.method	请求方法
  				req.path	请求路径
  				req.body	POST请求参数
				return res.status(200).json({...})  返回数据
				next();		最后需要调用next()跳转到下一个中间件
  			}
  		
  		注意:fetch请求需要添加headers
  			headers: {
	        	'Content-Type':'application/json'
	        },
  	
  		启用中间件:在命令中添加	--middlewares 文件路径
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值