【问题标题】:Node/Express: Database being printed on screen rather than index.htmlNode/Express:数据库打印在屏幕上而不是 index.html
【发布时间】:2021-12-16 19:15:07
【问题描述】:

所以,我使用的是 Node,但屏幕上打印的只是我的 JSON 格式的数据库,而不是 index.html。当我使用 localhost 时不会发生这种情况,所以我不知道为什么它会显示我的索引页面。谁能帮帮我?

我的代码:

const app = express();
app.listen(3000, () => console.log('listening'));

app.get('/api', (request, response) => {
    db.find({}, (err, data) => {
        response.json(data);
    });
});

【问题讨论】:

    标签: javascript node.js json express cpanel


    【解决方案1】:

    我没有完全正确理解您的问题,但根据代码,您将在 localhost:3000/api 上收到 JSON 响应,在 localhost:300 上收到空白屏幕,因为您尚未在代码中呈现或调用任何视图。

    您可以使用app.use(express.static(__dirname + '/public')) 访问您的目录,然后使用res.sendFile('index.html') 在您希望的任何路径上呈现索引 HTML 文件。

    【讨论】:

    • 感谢您的意见!我应该把这些放在我的 app.js 的什么地方?
    • 嘿!您已经有了 express.static 行,很抱歉在写答案时错过了它。只需在任何路由中写入res.sendFile('index.html'),在这种情况下,在您的/api 路由中。实际上,您的问题还说 DB 打印在屏幕上而不是 index.html ,这意味着您希望此 DB 在索引文件上。为此,您需要使用 API 将数据库专门调用到您的 HTML 文件中并在其中显示。
    猜你喜欢
    • 2010-12-23
    • 2012-08-20
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多