我正在尝试在 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]:错误:ENOENT:没有这样的文件或目录,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"
}
}
答案 0 :(得分:1)
几个月前,我在 Heroku 上部署了我的 MEAN 应用程序,因此我将与您分享我的配置。
在 angular.json 中找到 "outputPath" 并将其设置为您的服务器的 public/static 文件夹。在我的是"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 位于服务器文件夹以及 static 文件夹内