json-server的post如何请求?

使用json-server进行前端搬砖工作,get请求正常,使用post请求时控制台报错,状态码500(internal server error)
求问,有填过坑的大神来解答一下吗?

阅读 16.1k
3 个回答

刚刚试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不能重复
clipboard.png

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"
    }
  ]
新手上路,请多包涵

用put就可以,还没弄清post怎么搞

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题