我有用于在前端测试的假 api。
我已经看到在 json-server 包中放置或发布您的数据需要 id,我的问题是我可以使用不同的密钥而不是 id 作为 ex。
{
id: 1, ---> i want to change this with my custom id
name: 'Test'
}
我有用于在前端测试的假 api。
我已经看到在 json-server 包中放置或发布您的数据需要 id,我的问题是我可以使用不同的密钥而不是 id 作为 ex。
{
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
of request 应该设置为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'
});
去testDb
看看结果。添加了新块。--id key
id 使用控制台 cmd 中指定的所需名称自动添加。
{
"body": "body",
"description": "description",
"customId": 12
}
瞧!
在需要自定义 id 的情况下,我想出了使用自定义路由:json-server --watch db.json --routes routes.json
路线.json:
{ "/customIDroute/:cusomID" : "/customIDroute?cusomID=:cusomID" }
如果您使用server.js
文件启动服务器(在文档中server.js
了解更多信息),您可以像这样定义自定义 ID 路由
// server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
server.use(middlewares)
// custom routes
server.use(jsonServer.rewriter({
"/route/:id": "/route?customId=:id"
}))
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
您将使用以下命令启动服务器:
node server.js