我无法让 localhost:3001/api/notes 显示任何内容

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

所以我的server.js代码如下:

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}!`);
});

db.json文件如下:

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

在终端中 运行 npm start 并转到 localhost:3001/api/notes 它应该显示 db.json 的内容,但它只是显示一个空白页。谁能告诉我我做错了什么?

当我将 res.json(result) 替换为 res.send('Hello') 时,它显示“Hello”就好了,这让我相信 db.json 连接到 server.js

请帮忙?

除非您的 db.json 文件中有 notes 属性,否则无需在声明期间将您的 notes 变量括起来。

改为使用:

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

如果你使用

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

这与尝试访问 json 文件的 notes 属性 相同,你已经显示 none 所以我假设它是空白的。

You can read more on destructuring assignments here

您的问题在于如何导入 JSON 文件。假设您的 JSON 文件具有路径 db/db.json,请替换此行:

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

这个:

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