【问题标题】:doing POST - using custom id in JSON Server做 POST - 在 JSON 服务器中使用自定义 id
【发布时间】:2021-04-10 00:14:05
【问题描述】:

我有一个文件夹,在该文件夹中我有server.js,这是他们网站上提供的默认值

// server.js
const jsonServer = require('json-server') //1
const server = jsonServer.create()//2
const router = jsonServer.router('db.json')//3
const middlewares = jsonServer.defaults()//4
 
server.use(middlewares) //5

// To handle POST, PUT and PATCH you need to use a body-parser. Using JSON Server's bodyParser
server.use(jsonServer.bodyParser);
server.use(router) //6
server.listen(5000, () => {//7
  console.log('JSON Server is running')
})

在我的 db.json 中,没有“id”而是“employeeid”

我使用命令 node server --id employeeid db.json 启动我的 json 服务器

当我执行 GET 时,它可以工作。但是当我做一个 POST 时(在请求正文中只发送 fname 和 lname 但没有employeeid,因为我假设 jsonserver 必须自动生成employeeid)我收到一个错误,上面写着“id”未定义。

我的db.json 看起来像

 {
  "employees": [
    {
      "employeeid": 1,
      "fname": "manju",
      "lname": "s"
    },
    {
      "employeeid": 2,
      "fname": "albert",
      "lname": "dawson"
    }

谁能帮忙

【问题讨论】:

    标签: reactjs json-server


    【解决方案1】:

    我在这里看到的问题是运行命令:node server --id employeeid db.json

    您需要使用触发命令行实用程序的json-server。所以像下面这样的东西会给你想要的结果:

    $> npx json-server --id employeeid --p 5000 db.json
    
    

    【讨论】:

    • 实际上这个已解决的问题,但由于某种原因,如果我使用上述命令启动服务器,重写将不起作用。我已经针对同一 stackoverflow.com/questions/65560532/… 提出了单独的问题,请阅读我在此处添加的评论
    【解决方案2】:

    根据文档:如果您需要添加身份验证、验证或任何行为,您可以将项目作为模块与其他 Express 中间件结合使用

    运行命令node server --id employeeid db.json时不传递选项

    如果您想将id 更改为employeeid,您可以使用router

    const router = jsonServer.router('db.json');
    router.db._.id = 'employeeid';
    

    然后运行node server.js

    【讨论】:

      猜你喜欢
      • 2021-04-09
      • 2021-09-20
      • 2017-12-20
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 2016-02-22
      相关资源
      最近更新 更多