Получение ошибки «Ошибка: ENOENT: нет такого файла или каталога» в Heroku при доступе к HTML-странице с Node.JS

#html #node.js #express #heroku

Вопрос:

Я развернул index.html страницу с помощью Node.JS in Heroku . Это файловая структура, которой я следую в 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'
 

Я не понимаю, почему возникает эта ошибка. У меня есть index.html файл в public папке.

Поэтому, чтобы понять путь к героку, я добавил следующие строки в 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' ?

Также я пробовал express.static метод в server.js подобных

 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 что я здесь делаю не так ?

Ответ №1:

Попробуйте использовать:

 res.sendFile(path.join(__dirname, 'public', 'index.html'));
 

Комментарии:

1. получение ошибки sam Error: ENOENT: no such file or directory, stat '/app/public/index.html'