How can I get an object by id using json-server?

1k Views Asked by At

I'm trying to fetch an object by id using json-server. When I return just one variable(one json) in module.exports of database file, it works. But, if I return an object of multiple variables, i get a 404.

The resources are: http://localhost:3000/users http://localhost:3000/admins

GET users returns 200 in both cases. GET admins returns 200 in both cases. But GET users/1234 returns 404 when trying to return multiple json files.

The database file db.js:

var users  = require('./users.json');
var admins = require('./admins.json');

module.exports = function() {
return {
    users  : users,
    admins : admins
 } ; // With this 'GET users' or 'GET admins' works, but 'GET users/1234' don't
 // return users; // With this return, it works GET users, GET admins and GET users/1234 
}

The json file users.json:

{
    "users": [
        {
            "id": 1234,
            "name": "Andrew Owen",
            "age": 26,
            "eyeColor": "blue"
        },
        {
            "id": 1235,
            "name": "Susan prueba",
            "age": 45,
            "eyeColor": "hazel"
        }
     ]
}

command: json-server --watch db.js

2

There are 2 best solutions below

1
SHAIK ABRAR UL HAQ On

Actually id is created by default by the json server if you wont provided and it gives default sequential values from 1,2,3,4...

For me, it worked as id is provided by json-server when I fetched GET users/1.

0
Prathviraj Prabhu On

Just pass the id to the fetch function to get the user detail of particular id :

fetch(`http://localhost:3000/users?id=${val}`);