如何修复 Heroku 部署中的 Not Found 错误

How to Fix Not Found Error with Heroku Deployment

我是网络开发的新手,在使用 Heroku 部署我的非常基本的网站时遇到了一些问题。创建我的应用程序后,我已成功将我的应用程序推送到 git 并将其部署到 Heroku。此外,它在本地 运行 也很好。

但是,在打开应用程序时(使用 "Heroku open" 命令并单击 Heroku 应用程序页面上的 "Open app" 按钮),我收到一个显示 Not Found 的页面.

我一直在寻找解决方案,非常感谢这里的帮助。谢谢你。

过程文件:

web: node server.js

package.json:

 {                                                                               
   "name": "LHSite",                                                           
   "version": "1.0.0",                                                         
   "engines": {                                                                
       "node": "13.12.x"                                                       
   },                                                                          
   "scripts": {                                                                
       "start": "node server.js"                                               
   },                                                                          
   "dependencies": {                                                           
      "express": "4.17.1"                                                     
   },                                                                          
   "author": "Hunter Estrada",                                                 
   "license": "ISC"
 }

server.js:

var express = require('express');
var app = express();
var port = process.env.PORT || 8080
app.use(express.static(__dirname));
app.get("/", function(req, res) {
    res.sendFile("/Users/<user>/CS/LHSite/Apr29Home.html");
}
app.listen(port, function() {
    console.log("app running");
}

文件结构: file structure for my website

这是我的应用的 url:https://lh-anni-2.herokuapp.com

express.static 中间件与 res.sendFile 是分开的,您需要 直接使用 res.sendFile 的绝对路径。你可以做到:

  1. 在当前项目文件夹中创建一个 public 目录并将您的 html 文件放在那里。

  2. 在 server.js 文件中包含路径模块,如

const path = require('path');

  1. 用下面的代码行替换你的res.sendFile

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

注意:__dirname returns当前执行脚本所在的目录。