我已经在Heroku
中的Node.JS
的帮助下部署了index.html
页面。这是我在Heroku 中遵循的文件结构
-- Index.js
-- public
-- css
-- index.css
-- JS
-- index.js
-- index.html
-- home.html
-- procfile
-- package.json
在服务器脚本index.js
中
//express
const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000
const path = require('path')
app.get('/', function (req, res) {
console.log("Current directory:", __dirname);
console.log("filename: ", __filename);
//serve the html page
res.sendFile(path.join(__dirname, '/public/index.html'));
});
app.listen(PORT, () => {
console.log(`Listening on ${PORT}`);
});
在部署代码并运行server.js文件后,我得到了以下错误
Error: ENOENT: no such file or directory, stat '/app/public/index.html'
我不明白为什么会出现这个错误。我在public
文件夹中有一个index.html
文件。
因此,为了了解heroku的路径,我在server.js
文件中添加了以下行
console.log("Current directory:", __dirname); // return the path
console.log("filename: ", __filename); // return the index.js file path
相应的输出如下:
Current directory: /app
filename: /app/index.js
现在/app
是应用程序的主目录。那么为什么res.sendFile(path.join(__dirname, '/public/index.html'));
会返回error no such file or directory, stat '/app/public/index.html'
呢?
我也在server.js
中尝试过类似的express.static
方法
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile('index.html');
});
然后我得到了新的错误
TypeError: path must be absolute or specify root to res.sendFile
在那之后,我又尝试了一种方法
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile('public/index.html', { root: __dirname });
});
然后我得到了相同的错误Error: ENOENT: no such file or directory, stat '/app/public/index.html'
有什么建议吗?如何访问index.html
和home.html
我在这里做错了什么?
尝试使用:
res.sendFile(path.join(__dirname, 'public', 'index.html'));