Search code examples
javascriptjson-server

Cannot read url parameters from json-server when data received is an array


I'm trying to build a fake api with json-server and facing an issue. I don't know if I'm missing something or if I just hit a bug.

Basically, if I send a url parameter when requesting data received as a single object, I can then read my parameter just fine when I'm trying to render that data.

But if the data that I receive is an array, then I get undefined trying to read that parameter.

These are my files (don't mind the logic behind this, I simplified things to reduce unnecessary information).

server.js

const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router(require('./db.js')())
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)

router.render = (req, res) => {
    console.log("User try query: " + req.query.user)
    console.log("User try param: " + req.params['user'])

    if (req.url.startsWith('/slack_users_info')) {
      res.jsonp({
        user: res.locals.data
      })

    } else if (req.url.startsWith('/slack_users_info2')) {
      res.jsonp({
        user: res.locals.data
      })

    } else {
        res.jsonp(res.locals.data)
    }
}

server.use(router)

// Run server on indicated port.
server.listen(port = 3000, () => {
    console.log('JSON Server is running')
    console.log('http://localhost:' + port)
})

db.js

var faker = require('faker');

module.exports = function () {
    var data = {
        slack_users_info: slack_users_info(),
        slack_users_info2: slack_users_info2()
    }

    return data;
}

function slack_users_info() {
    subdata = []

    for (var i = 0; i < 10; i++) {
        subdata.push({
            id: "user_id_" + i,
        })
    }

    return subdata;
}

function slack_users_info2() {

    subdata = {
        id: "user_id"
    }

    return subdata;
}

I'm running with npm start.

If I request the array, I get undefined: GET http://localhost:3000/slack_users_info?user=user_id_0 Then I get:

User try query: undefined
User try param: undefined

If I request the single object I get the expected parameter: GET http://localhost:3000/slack_users_info2?user=user_id_0 Then I get:

User try query: user_id_0
User try param: undefined

In both cases the response body is received correctly, I just can't read the parameter in the first case.

Is there a reason for this?


Solution

  • Looking at https://www.npmjs.com/package/json-server#generate-random-data it seems like you need to return an object, but can include your array inside that object.

    For example, try:

    function slack_users_info() {
      const data = {
        users: []
      }
    
      for (var i = 0; i < 10; i++) {
        data.users.push({
          id: "user_id_" + i,
        })
      }
      return data;
    }