使用Node.js在json服务器中自定义路由

时间:2018-09-20 16:16:09

标签: json node.js json-server

使用自定义路由请求在json服务器中部署的db.json时发现问题。

例如,对于以下给定的json,我想按名称访问选民,所以当我键入 网址:

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

sessionIdvoterNameparameterized的位置,响应应为{"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)

预先感谢您的回答。

2 个答案:

答案 0 :(得分:1)

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

您可以尝试:

.bashrc

答案 1 :(得分:0)

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