在我们平时开发中,特别是需要与接口打交道时,无论是写接口还是用接口,拿到接口后肯定都得提前测试一下,这样的话就非常需要有一个比较给力的Http请求模拟工具,现在流行的这种工具也挺多的,像火狐浏览器插件-RESTClient,Chrome浏览器插件-Postman等等。我使用的是Postman。
JSON-Server 是一个 Node 模块,运行 Express 服务器,你可以指定一个 json 文件作为 api 的数据源。
使用postman进行接口的测试比较简单,同时还可以看某站的视频,20分钟就可以进行使用了,链接在这里:
json-server使用教程
使用json-server与postman进行接口测试
写这篇文章主要记录一下自己在项目的开发过程中遇到的问题。
我先用json-server在本地生成了一个json文件,内容如下:
然后我想通过post方式向该接口发送数据:
填写信息之后,将所填写的信息发送到json-server模拟的服务器端。
代码如下:
<form v-on:submit="addTeach">
<div class="well">
<h4>请填写以下信息</h4>
<div class="form-group">
<label>姓名</label>
<input type="text" class="form-control" v-model="tinfo.name" placeholder="name"/>
</div>
<div class="form-group">
<label>课程总数</label>
<input type="text" class="form-control" v-model="tinfo.cnum" placeholder="class"/>
</div>
<div class="form-group">
<label>联系方式</label>
<input type="text" class="form-control" v-model="tinfo.phone" placeholder="phone"/>
</div>
<button type="submit" class="btn btn-success center-block">添加</button>
</div>
</form>
methods:{
addTeach(e){
console.log("123");
if(!this.tinfo.name || !this.tinfo.cnum || !this.tinfo.phone) {
console.log("456");
} else {
//console.log("newtinfo");
var newtinfo = {};
newtinfo = {
name:this.tinfo.name,
cnum:this.tinfo.cnum,
phone:this.tinfo.phone
};
console.log(newtinfo);
this.$http.post('http://localhost:3000/users',newtinfo).then(
function(response) {
console.log(response);
this.$router.push({path:"/",query:{alert:"添加成功"}});
})
}
e.preventDefault();
}
}
代码没有问题,不管怎么测试,都会报如下错误(500说明是服务器端出错):
TypeError: Cannot read property 'id' of undefined
at Function.createId (D:\json-server\node_modules\json-server\lib\server\mixins.js:57:39)
at Function.insert (D:\json-server\node_modules\lodash-id\src\index.js:47:49)
at D:\json-server\node_modules\lodash\lodash.js:4368:28
at arrayReduce (D:\json-server\node_modules\lodash\lodash.js:683:21)
at baseWrapperValue (D:\json-server\node_modules\lodash\lodash.js:4367:14)
at LodashWrapper.wrapperValue (D:\json-server\node_modules\lodash\lodash.js:9050:14)
at create (D:\json-server\node_modules\json-server\lib\server\router\plural.js:235:48)
at Layer.handle [as handle_request] (D:\json-server\node_modules\express\lib\router\layer.js:95:5)
at next (D:\json-server\node_modules\express\lib\router\route.js:137:13)
at next (D:\json-server\node_modules\express\lib\router\route.js:131:14)
POST /users 500 16.042 ms - 874
主要是这一句Cannot read property ‘id’ of undefined。网上有很多方法,但都没有解决我的问题,后来经过排查,发现在最开始新建这个json文件的时候,每条数据都有个“id”属性,但在做项目的时候,并没有把这个"id"属性添加给数据。然后我把json文件修改了一下,给每条数据都加了个"id",就不会报错了。
而且在项目中,给服务器端传数据的时候,不需要自己填写这个"id"属性的值,这个id是json自动分配的。