【问题标题】:Custom routes in json-server using Node.js使用 Node.js 在 json-server 中自定义路由
【发布时间】:2019-02-25 00:17:03
【问题描述】:

我在使用自定义路由请求部署在 json-server 中的 db.json 时发现问题。

例如对于下面这个给定的 json,我想按名字访问选民,所以当我输入这个 网址:

https://localhost:3000/data/1/sessions/:sessionId/voters/:voterName

sessionIdvoterName在哪里parameterized,响应应该是{"voterName"}

db.json

{
  "id": 1,
  "name": "Angular Connect",
  "date": "2036-09-25T23:00:00.000Z",
  "time": "10:00 am",
  "price": 599.99,
  "imageUrl": "/assets/images/angularconnect-shield.png",
  "location": {
    "address": "1057 DT",
    "city": "London",
    "country": "England"
  },
  "sessions": [
    {
      "id": 1,
      "name": "Using Angular 4 Pipes",
      "presenter": "Peter Bacon Darwin",
      "duration": 1,
      "level": "Intermediate",
      "abstract": "Learn all about the new pipes in Angular 4, both \n        how to write them, and how to get the new AI CLI to write \n        them for you. Given by the famous PBD, president of Angular \n        University (formerly Oxford University)",
      "voters": [
        "bradgreen",
        "igorminar",
        "martinfowler"
      ]
    },
    {
      "id": 2,
      "name": "Getting the most out of your dev team",
      "presenter": "Jeff Cross",
      "duration": 1,
      "level": "Intermediate",
      "abstract": "We all know that our dev teams work hard, but with \n        the right management they can be even more productive, without \n        overworking them. In this session I'll show you how to get the \n        best results from the talent you already have on staff.",
      "voters": [
        "johnpapa",
        "bradgreen",
        "igorminar",
        "martinfowler"
      ]
    },
    {
      "id": 3,
      "name": "Angular 4 Performance Metrics",
      "presenter": "Rob Wormald",
      "duration": 2,
      "level": "Advanced",
      "abstract": "Angular 4 Performance is hot. In this session, we'll see \n        how Angular gets such great performance by preloading data on \n        your users devices before they even hit your site using the \n        new predictive algorithms and thought reading software \n        built into Angular 4.",
      "voters": []
    },
    {
      "id": 4,
      "name": "Angular 5 Look Ahead",
      "presenter": "Brad Green",
      "duration": 2,
      "level": "Advanced",
      "abstract": "Even though Angular 5 is still 6 years away, we all want \n        to know all about it so that we can spend endless hours in meetings \n        debating if we should use Angular 4 or not. This talk will look at \n        Angular 6 even though no code has yet been written for it. We'll \n        look at what it might do, and how to convince your manager to \n        hold off on any new apps until it's released",
      "voters": []
    },
    {
      "id": 5,
      "name": "Basics of Angular 4",
      "presenter": "John Papa",
      "duration": 2,
      "level": "Beginner",
      "abstract": "It's time to learn the basics of Angular 4. This talk \n        will give you everything you need to know about Angular 4 to \n        get started with it today and be building UI's for your self \n        driving cars and butler-bots in no time.",
      "voters": [
        "bradgreen",
        "igorminar"
      ]
    }
  ]
}

为了显示最后的结果,我在 NodeJS 中使用了自定义路由,如下所示:

router.js

var jsonServer = require('json-server')
const low = require('lowdb')
var server = jsonServer.create()
const db = low('db.json')

// Add custom routes before JSON Server router
server.get('/data/:id/sessions/:sessionId/voters/:voterName', function (req, res) {
  // See https://github.com/typicode/lowdb
var user=db.get("sessions")
           .find({id:sessionId})
           .get("voters") 
           .find({voterName})
           .value()
  if (user) {
    res.jsonp(user)
  } else {
    res.sendStatus(404)
  }
})

server.use(function (req, res, next) {
  if (req.method === 'POST') {
    req.body.createdAt = Date.now()
  }
  // Continue to JSON Server router
  next()
})

// Use default router
// server.use(router)
server.listen(3000, function () {
  console.log('JSON Server is running')
})

但是当我运行这个命令时:

json-server --watch db.json --middlewares router.js

我收到以下错误:

TypeError: app.use() requires a middleware function
    at Function.use (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\node_modules\express\lib\application.js:210:11)
    at createApp (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:79:9)
    at load (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:148:13)
    at module.exports (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\utils\load.js:37:5)
    at start (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:125:5)
    at module.exports (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:162:3)
    at module.exports (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\index.js:81:3)
    at Object.<anonymous> (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\bin.js:3:14)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)

提前感谢您的回答。

【问题讨论】:

    标签: json node.js json-server


    【解决方案1】:

    我认为你不应该使用 --middlewares 选项来启动你的服务器,router.js 不是一个中间件。所以在这里它尝试将你的 router.js 添加为中间件并且无法启动

    你可以试试:

    json-server router.js --watch db.json 
    

    【讨论】:

      【解决方案2】:

      使用json服务器有两种选择,一种是通过你自己的js文件运行它,另一种是通过运行中间件你正在运行js文件你应该运行中间件,这样https://github.com/typicode/json-server#add-middlewares只创建module.export如链接所示。您不需要所有花哨的服务器。

      【讨论】:

        猜你喜欢
        • 2022-11-08
        • 2020-04-17
        • 2022-06-21
        • 1970-01-01
        • 2019-09-15
        • 2019-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多