【发布时间】: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 会话,您可以使用它在文件系统中使用ls和cd,以查看应该存在的文件/目录是否存在。另外,请记住检查您是否确保 Heroku 确实构建了您的dist代码/文件/等,而不是仅仅运行npm start。
标签: node.js angular express heroku