使用json-server进行前端搬砖工作,get请求正常,使用post请求时控制台报错,状态码500(internal server error)
求问,有填过坑的大神来解答一下吗?
使用json-server进行前端搬砖工作,get请求正常,使用post请求时控制台报错,状态码500(internal server error)
求问,有填过坑的大神来解答一下吗?
刚刚试mock
用了这个json-server
也遇到post
请求报错 研究了一番 解决如下
官网上说
A POST, PUT or PATCH request should include a Content-Type:
application/json header to use the JSON in the request body. Otherwise
it will result in a 200 OK but without changes being made to the data.
也就是说 要完成post
请求
1.请求的header
要包含Content-Type:application/json
2:要用json
的格式去提交 而不是表单
还有一个就是提交的id
不能重复,不然会报错400
我用的axios
需要在axios(config)执行之前进行数据变换 加上以下两句params
就是要传的参数
params: {"id":"3", "title": "update title", "author": "dongzhe"}
config.headers = Object.assign({}, headers, {'Content-Type': "application/json"})
config.transformRequest = [function (data) {
data = JSON.stringify(params)
return data;
}]
最后的请求结果和图片一样,他是动态的往db.json
来添加,id
不能重复
post之前是这样
[
{
"id": 1,
"title": "json-server",
"author": "typicode"
},
{
"id": 2,
"title": "json-server2",
"author": "typicode2"
}
]
post之后是这样
[
{
"id": 1,
"title": "json-server",
"author": "typicode"
},
{
"id": 2,
"title": "json-server2",
"author": "typicode2"
},
{
"id": "3",
"title": "update title",
"author": "dongzhe"
}
]
10 回答11.1k 阅读
2 回答11.5k 阅读✓ 已解决
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
我碰到post请求会清空db.json中的数据,官网有说明:https://github.com/typicode/j...
还在看官网文档。