json-server error: "Cannot create property 'id' on string"

31 Views Asked by At

I'm using json-server to run a mock server while I develop my front-end. I have a hardcoded file db.json which contains

{
    "a": ["b"]
}

I want to make a fetch request to the mock server to retrieve the array from db.json.

I install json-server like this

$ npm install -g json-server

and to start the mock server, i run this command in my terminal

$ json-server db.json --port 5500

The mock server fails immediately. It gives me this error message:

file:///root/.nvm/versions/node/v16.20.2/lib/node_modules/json-server/lib/service.js:87
            item['id'] = randomId();
                       ^

TypeError: Cannot create property 'id' on string 'b'
    at file:///root/.nvm/versions/node/v16.20.2/lib/node_modules/json-server/lib/service.js:87:24
    at Array.forEach (<anonymous>)
    at fixItemsIds (file:///root/.nvm/versions/node/v16.20.2/lib/node_modules/json-server/lib/service.js:82:11)
    at file:///root/.nvm/versions/node/v16.20.2/lib/node_modules/json-server/lib/service.js:95:13
    at Array.forEach (<anonymous>)
    at fixAllItemsIds (file:///root/.nvm/versions/node/v16.20.2/lib/node_modules/json-server/lib/service.js:93:25)
    at new Service (file:///root/.nvm/versions/node/v16.20.2/lib/node_modules/json-server/lib/service.js:102:9)
    at createApp (file:///root/.nvm/versions/node/v16.20.2/lib/node_modules/json-server/lib/app.js:17:21)
    at file:///root/.nvm/versions/node/v16.20.2/lib/node_modules/json-server/lib/bin.js:116:13

Of note, I get no error if I change db.json contents to

{
    "a": "b"
}

It seems to me that json-server is assuming that the data in the array is a javascript object. Are arrays of strings not valid?

How can I get json-server to work with my data?

1

There are 1 best solutions below

0
Evan D Losh On

I just found the solution. My data has to be nested in a an endpoint. I changed my db.json file to this:

{
    "this-is-the-name-of-an-endpoint":
        {
            "a": ["b"]
        }
}

And then I was able to run json-server on this file.