3

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

例如对于如下给定的 json,我想按名称访问选民,所以当我输入这个 url 时:

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

where aresessionIdvoterNameare 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 中使用了自定义路由,如下所示:

路由器.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)

提前感谢您的回答。

4

2 回答 2

2

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

你能试试:

json-server router.js --watch db.json 
于 2018-09-20T20:58:12.480 回答
0

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

于 2018-11-01T17:09:02.070 回答