我有假的 api 用于前端测试。
我已经看到 id 需要在 json-server 包中放置或发布您的数据,我的问题是我可以使用不同的密钥而不是 id 来代替 id 吗?
{
id: 1, ---> i want to change this with my custom id
name: 'Test'
}
Run Code Online (Sandbox Code Playgroud)
小智 7
让我们看看json-server包的CLI 选项:
$ json-server -h
...
--id, -i Set database id property (e.g. _id) [default: "id"]
...
Run Code Online (Sandbox Code Playgroud)
让我们尝试使用名为“ customId ”的新 id 启动 json-server (例如):
json-server --id customId testDb.json
testDb.json文件的结构:$ cat testDb.json
{
"messages": [
{
"customId": 1,
"description": "somedescription",
"body": "sometext"
}
]
}
Run Code Online (Sandbox Code Playgroud)
通过$.ajax
函数(或通过 Fiddler/Postman/等)发出一个简单的 POST 请求。Content-type
请求应设置为application/json
- 可以在该项目的 github 页面上找到解释:
POST、PUT 或 PATCH 请求应包含 Content-Type: application/json 标头以在请求正文中使用 JSON。否则将导致 200 OK 但不会对数据进行更改。
所以...从浏览器发出请求:
$.ajax({
type: "POST",
url: 'http://127.0.0.1:3000/messages/',
data: {body: 'body', description: 'description'},
success: resp => console.log(resp),
dataType: 'json'
});
Run Code Online (Sandbox Code Playgroud)
去testDb
看看结果。添加了新块。id 自动添加了在--id key
控制台 cmd 中指定的所需名称。
{
"body": "body",
"description": "description",
"customId": 12
}
瞧!
小智 5
我想出了在需要自定义 id 的情况下使用自定义路由: json-server --watch db.json --routes paths.json
路线.json:
{ "/customIDroute/:cusomID" : "/customIDroute?cusomID=:cusomID" }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6290 次 |
最近记录: |