【发布时间】:2019-10-29 03:10:00
【问题描述】:
我有一个带有 Universal 的 Angular 8 应用程序,我想将它部署到共享的 Web 主机生产服务器。我事先与网络主机核对过,他们告诉我可以在他们的共享网络主机上托管一个 Angular 通用网络应用程序。但是,无论我做什么,我都无法让网站正常工作。当我访问该网站时,我不断看到消息:“无法访问此网站”
到目前为止我做过的事情:
- 使用 npm run build:ssr 构建项目,它创建了一个 dist 文件夹,其中包含一个浏览器和服务器文件夹以及一个 server.js 文件
- 将 dist 文件夹移动到服务器的 public_html 文件夹内。 然后通过 SSH 访问服务器并执行以下操作:
- 安装 Node.js 和 npm
- npm 安装
- npm install pm2 -g
- pm2 启动 dist/server.js
pm2 启动没有问题。
这些是一些项目文件。如果有任何遗漏,请询问,我会将它们添加到问题中。
包含脚本的 package.json 的一部分:
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"compile:server": "webpack --config webpack.server.config.js --progress --colors",
"serve:ssr": "node dist/server",
"build:ssr": "npm run build:client-and-server-bundles && npm run compile:server",
"build:client-and-server-bundles": "ng build --prod && ng run ProjectName:server:production --bundleDependencies all"
},
构建中的 server.js(只有 express 部分,因为它有 25000 多行):
const app = express__WEBPACK_IMPORTED_MODULE_1__();
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = Object(path__WEBPACK_IMPORTED_MODULE_2__["join"])(process.cwd(), 'dist/browser');
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP, ngExpressEngine, provideModuleMap } = __webpack_require__(144);
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', DIST_FOLDER);
// Example Express Rest API endpoints
// app.get('/api/**', (req, res) => { });
// Serve static files from /browser
app.get('*.*', express__WEBPACK_IMPORTED_MODULE_1__["static"](DIST_FOLDER, {
maxAge: '1y'
}));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render('index', { req });
});
// Start up the Node server
app.listen(PORT, () => {
console.log(`Node Express server listening on http://localhost:${PORT}`);
});
根据 SO 或其他地方的几个答案,您“简单地”将 dist 文件夹复制粘贴到服务器,运行 pm2 并且您的网站应该可以正常工作。不过,我觉得要让它发挥作用还缺少很多东西。
有人知道如何将 Angular Universal 网站正确部署到生产服务器吗?
【问题讨论】:
-
您的共享主机是否有您可以配置的网络服务器,例如Apache 还是 nginx?
-
直接访问 http://ip-adres 可以看到 Apache 正在运行
-
你能在 apache 中创建一个虚拟主机吗?从技术上讲,您需要将流量从 Apache 配置重定向到您的 nodejs 服务器
-
不知道该怎么做。我会试着弄清楚。我需要在某个配置文件中这样做吗?
-
这取决于您的托管公司。有时您必须使用
.htaccess文件来完成此操作
标签: node.js angular pm2 angular-universal