npm - json-server 我们可以使用其他键而不是 id 来发送和放置请求吗

标签 npm json-server

我有假的 api 用于前端测试。

我已经看到 id 需要在 json-server 包中放置或发布您的数据,我的问题是我可以使用不同的 key 而不是 id 来代替 id 吗?

{
  id: 1, ---> i want to change this with my custom id
  name: 'Test'
} 

最佳答案

让我们看看 json-server 包的 CLI 选项:$ json-server -h

...
--id, -i   Set database id property (e.g. _id)   [default: "id"]
...

让我们尝试使用名为“ customId ”的新 ID 启动 json-server(例如):json-server --id customId testDb.json
testDb.json 文件的结构:$ cat testDb.json
{
  "messages": [
    {
      "customId": 1,
      "description": "somedescription",
      "body": "sometext"
    }
  ]
}

通过 $.ajax 函数(或通过 Fiddler/Postman/等)发出一个简单的 POST 请求。请求的 Content-type 应设置为 application/json - 可以在该项目的 github 页面上找到解释:

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.



所以...从浏览器发出请求:
$.ajax({
  type: "POST",
  url: 'http://127.0.0.1:3000/messages/',
  data: {body: 'body', description: 'description'},
  success: resp => console.log(resp),
  dataType: 'json'
});

转到 testDb 并查看结果。添加了新块。 id 自动添加了在控制台 cmd 的 --id key 中指定的所需名称。
{ "body": "body", "description": "description", "customId": 12 }
瞧!

关于npm - json-server 我们可以使用其他键而不是 id 来发送和放置请求吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43278348/

相关文章:

javascript - 无法在 JSON-SERVER 中获取对象关键数据

npm - 如何npm install-保存所有已安装的软件包?

gruntjs - npm install 未安装任何软件包

node.js - 右键单击时看不到 "Manage npm modules"

angular - 使用相同的启动脚本运行 Angular 应用程序和 JSON 服务器

json-server - 将 json-server 重置为 db.json 的内容

npm - (安全)使用 gitlab CI 进行 npm 审计

angular - 如何使用 grunt 部署 Angular 2?

json - 使用 Node.js 在 json-server 中自定义路由

angular - json-server 中嵌套端点的自定义路由