Home > Enterprise >  I can't get localhost:3001/api/notes to display anything
I can't get localhost:3001/api/notes to display anything

Time:01-02

So my server.js code is as follows:

const express = require('express');

const PORT = process.env.PORT || 3001;
const app = express();
const { notes } = require('./db/db');

app.get('/api/notes', (req, res) => {
    const result = notes;
    res.json(result);
});

app.listen(PORT, () => {
    console.log(`API server now on port ${PORT}!`);
});

The db.json file is as follows:

[
    {
        "title":"Test",
        "text":"Test"
    }
]

After running npm start in terminal and going to localhost:3001/api/notes it supposed to show the contents of db.json, but it is just showing a blank page. Can anyone tell me what I am doing wrong?

When i replaced res.json(result) with res.send('Hello') it displayed the "Hello" just fine which leads me to believe there is a problem with connecting db.json to server.js

Help Please?

CodePudding user response:

Unless there is a notes property of your db.json file there is no need to surround your notes variable during its declaration.

Instead use:

const notes = require('./db/db');

If you use

const { notes } = require('./db/db');

Its the same as trying to access the notes property of the json file, which youve shown none so I've assumed its blank.

You can read more on destructuring assignments here

CodePudding user response:

Your problem is in how you import the JSON file. Assuming your JSON file has path db/db.json, replace this line:

const { notes } = require('./db/db');

with this one:

const notes = require('./db/db.json');
  • Related