【问题标题】:Why am I getting 404 errors on my Mean production app?为什么我的平均生产应用程序出现 404 错误?
【发布时间】:2021-06-25 00:01:49
【问题描述】:

我正在尝试在 Heroku 上发布一个 node.js 服务器,它为所有请求(减去 /api 端点)提供一个角度应用程序。当我在本地机器上运行 node.js 服务器 + 在 Angular 应用程序上运行 ng build --watch 时,Angular 应用程序工作得非常好。我面临的问题是,当我将服务器推送到 Heroku 时,角度路由上出现 404 错误。

这是我在 Heroku 日志中遇到的错误:2021-03-28T20:38:50.700486+00:00 app[web.1]: Error: ENOENT: no such file or directory, stat '/app/客户端/dist/client/index.html'

在深入研究之后,我发现基于“npm run build”构建的 dist 文件没有部署到 heroku。在下面发布我的 package.json 文件。

这是我的服务器代码:

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
const path = require('path')
const api = require('./routes/api');

const cors = require('cors')
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use('/api', api)

app.use(express.static(__dirname + 'client/dist/client'));
app.get('**', function(req,res) {
res.sendFile(path.join(__dirname + 'client/dist/client/index.html'));

});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
    console.log((path.join( __dirname  + '/client/dist/client/index.html')))
  })

Package.Json:

{
  "name": "spotify-playlist",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.21.1",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1"
  }
}

【问题讨论】:

  • 似乎很清楚:client/dist/client/index.html 不存在于文件系统中(例如,在您的磁盘上)。因此,请确保您指向正确的目录/文件。
  • 当我在本地机器上运行“node index.js”时,它似乎工作正常。好像文件也存在。
  • 很酷,但您不是在询问本地设置,而是在询问 Heroku,因此:在线或 CLI 为您的应用程序启动 heroku 控制台)并找出 作为文件系统?
  • 对不起,我在这方面有点缺乏经验。我到底在 Heroku 上寻找什么?
  • 转到您的应用程序,然后在右上角有“更多...”菜单,单击它,然后选择控制台选项,然后告诉它运行bash。这将为您提供一个 bash 会话,您可以使用它在文件系统中使用lscd,以查看应该存在的文件/目录是否存在。另外,请记住检查您是否确保 Heroku 确实构建了您的 dist 代码/文件/等,而不是仅仅运行 npm start

标签: node.js angular express heroku


【解决方案1】:

几个月前,我在 Heroku 上部署了 MEAN 应用程序,因此我将与您分享我的配置。

angular.json 中找到 "outputPath" 并将其设置为您的情况下服务器的公共/静态文件夹。在我这里是"outputPath": "./server/static"

确保在服务器代码中将构建 Angular 应用程序的文件夹设置为 static。就我而言,我有以下几点:

app.use(express.static(path.resolve(__basedir, 'static')))

app.get('*', (req, res) => {
            res.status(200).sendFile(path.join(__basedir, '/static', 'index.html'))
        });

在 package.json 中你需要以下两个脚本:

"start": "node server/index.js" // This should point to your index.js file, whereever it is
"heroku-postbuild": "ng build --prod" // This one builds the angular app before your index.js serves it

附:忽略 server 文件夹 在我的例子中 index.js 位于 server 文件夹以及 static 文件夹

【讨论】:

    猜你喜欢
    • 2021-02-01
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2020-04-28
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多