json-server
json-server copied to clipboard
question: using as memory db inside nodejs app
I'm trying to use the server as a dev de inside other app, the get method returns undefined, but the data is in the json
is this correct ?
const db = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
db.use(middlewares);
db.use(router);
// get eventos
function getAllEventos() {
return db.get('eventos'); // returns undefined
}
the db
{
"eventos": [
{
"id": 1,
"nombre": "Concierto de Rock",
"precio": 25.99,
"fecha": "2023-06-15",
"descripcion": "Un increíble concierto de rock con bandas populares.",
"cantidad_maxima_entradas": 1000
},
{
"id": 2,
"nombre": "Exposición de Arte",
"precio": 10.50,
"fecha": "2023-07-05",
"descripcion": "Una exposición de arte contemporáneo con artistas reconocidos.",
"cantidad_maxima_entradas": 500
},
{
"id": 3,
"nombre": "Seminario de Desarrollo Web",
"precio": 50.00,
"fecha": "2023-08-20",
"descripcion": "Un seminario intensivo sobre las últimas tecnologías de desarrollo web.",
"cantidad_maxima_entradas": 200
}
]
}
Your code seems mostly correct, but the issue might be with how you're attempting to retrieve data using db.get('eventos'). The db.get method is typically used for retrieving a property from the Express app's settings.
If you want to retrieve all eventos from the router, you should use router.db.getState().eventos: `const db = jsonServer.create(); const router = jsonServer.router('db.json'); const middlewares = jsonServer.defaults();
db.use(middlewares); db.use(router);
// get eventos function getAllEventos() { return router.db.getState().eventos; } `
This way, getAllEventos should return an array with all the eventos from your JSON file.
Remember that json-server automatically creates routes for each resource in your JSON file, so you don't need to explicitly handle GET requests for each resource. If you want to retrieve all eventos, you can simply make a GET request to /eventos on your JSON-Server.
`const axios = require('axios');
axios.get('http://localhost:3000/eventos') .then(response => { console.log(response.data); }) .catch(error => { console.error(error); }); `
This will make a GET request to your JSON-Server running at http://localhost:3000 and fetch all eventos.