Custom routes in json-server using Node.js

14,538

I think you should not use the --middlewares options to start your server, router.js is not a middleware. so here it try to add your router.js as a middleware and fail to start

could you try :

json-server router.js --watch db.json 
Share:
14,538
Mohamed Aoutir
Author by

Mohamed Aoutir

Updated on June 23, 2022

Comments

  • Mohamed Aoutir
    Mohamed Aoutir almost 2 years

    I found problem when using custom routes for requesting db.json which is deployed in json-server.

    For example for this given json as below, I'd like to access voters by name, so when I type this url:

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

    Where are sessionId and voterName are parameterized, the response should be {"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"
          ]
        }
      ]
    }
    

    For showing the last result I used custom routes in NodeJS like below:

    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')
    })
    

    But when I run this command:

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

    I get the following error:

    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)
    

    Thanks in advance for your answer.