【问题标题】:"Cannot GET /" with res.sendFile() in Express在 Express 中使用 res.sendFile() “无法获取 /”
【发布时间】:2021-08-12 06:52:10
【问题描述】:

我正在尝试使用 res.sendFile 呈现 index.html,但我不太清楚这些路径是如何工作的。我在运行它时不断收到 "Cannot GET /"。我以前可以正常工作,但我移动了文件和文件夹,这次我没有找到成功的方法。

index.js 中的代码:

const options = {root: path.join(__dirname, "/screens/")};

app.get('/', function (req, res) {
    res.sendFile('index.html',options);
});

这是文件的排列方式:(我要渲染的 index.html 是屏幕文件夹中的那个)

非常感谢!

【问题讨论】:

    标签: express render


    【解决方案1】:

    我需要在此处进行哪些更改才能复制您正在做的事情? 这可行

    我的代码:

    index.js

    const express = require('express');
    const path = require('path');
    const http = require('http');
    
    const app = express();
    
    app.get('/', (req, res) => {
        res.sendFile('index.html', {root: path.join(__dirname, "/screens/")});
    });
     
    const httpServer = http.Server(app);
    
    httpServer.listen(8888, function () {
        console.log('Express server listening to port ' + httpServer.address().port);
    });
    

    screens/index.html

    Hi Pop, how are you?
    

    以上运行完美

    【讨论】:

    • 谢谢!我会试试的。感谢您的建议,我还应该分享什么?我试图分享与此事相关的所有内容,但也许我跳过了一些内容
    • 更新了上面的答案 - 第二次使其与您在问题中提出的相似。
    猜你喜欢
    • 2014-11-08
    • 2015-06-20
    • 2018-12-25
    • 2021-08-15
    • 2014-11-29
    • 2018-01-19
    • 2020-09-06
    • 2018-07-01
    • 2022-01-12
    相关资源
    最近更新 更多