【问题标题】:I can't get localhost:3001/api/notes to display anything我无法让 localhost:3001/api/notes 显示任何内容
【发布时间】:2022-01-01 23:11:09
【问题描述】:

所以我的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.send('Hello') 替换 res.json(result) 时,它显示“Hello”就好了,这让我相信将 db.json 连接到 server.js 时出现问题

请帮忙?

【问题讨论】:

    标签: node.js json express localhost


    【解决方案1】:

    除非你的db.json 文件有一个notes 属性,否则在声明期间不需要围绕你的notes 变量。

    改为使用:

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

    如果你使用

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

    这与尝试访问 json 文件的 notes 属性相同,您没有显示该属性,因此我假设它为空白。

    You can read more on destructuring assignments here

    【讨论】:

      【解决方案2】:

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

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

      用这个:

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

      【讨论】:

        猜你喜欢
        • 2014-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-10
        • 2011-12-31
        • 2018-12-16
        相关资源
        最近更新 更多