我有假的 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/