生产中的Angular SSR“无法查找视图”(Ubuntu,Nginx)

0le*_*leg 5 nginx express angular-universal ssr angular

跟进有关使用Express服务器设置SSR的官方Angular教程:https : //angular.io/guide/universal#configure-for-universal

本教程将设置如下路径:

...
const DIST_FOLDER = join(process.cwd(), 'dist');
...
app.set('views', join(DIST_FOLDER, 'browser'));
Run Code Online (Sandbox Code Playgroud)

这在本地服务器上效果很好。

但是,一旦部署在服务器上(由Nginx提供支持),就会出现错误:

错误:无法在ServerResponse.render(/ var / proj_name /)的Function.render(/var/proj_name/server.js:44670:17)的视图目录“ / home / user_name / dist / browser”中查找视图“索引”在Layer.handle的/var/proj_name/server.js:121:9处的server.js:53701:7)[在下一个(/ var / proj_name)处[作为handle_request](/var/proj_name/server.js:46582:5) /server.js:46330:13)位于Route.dispatch(/var/proj_name/server.js:46305:3)位于Layer.handle [作为handle_request](/var/proj_name/server.js:46582:5)位于/ param的/var/proj_name/server.js:45805:22(/var/proj_name/server.js:45878:14)at param(/var/proj_name/server.js:45889:14)

如何正确处理此问题,以便该应用程序既可以在本地(用于开发)又可以在生产服务器上正常运行?

编辑:

还尝试使用__dirname代替:

app.get(' ',express.static(join(__ dirname,'browser')));

但这在本地和生产服务器上均失败:

错误:无法在视图目录“ /浏览器”中查找视图“索引”

编辑2:

我已经设法通过将browser文件夹移到来完成这项工作~/dist/browser。但我不希望该应用程序以这种方式工作。

看起来失败的代码在server.ts中

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render('index', { req });
});
Run Code Online (Sandbox Code Playgroud)

在本地运行时,const DIST_FOLDER = join(process.cwd(), 'dist');返回正确的输出。但是,当在真实服务器(Ubuntu,Nginx)上运行时,它将得到:/home/<user_name>/dist/browser相反。使用__dirname没有帮助。

因此需要一些方法来确保res.render('index', { req });获取正确的资源。

Dav*_*vid 8

Using the following piece of code

const DIST_FOLDER = join(process.cwd(), 'dist');
app.set('views', join(DIST_FOLDER, 'browser'));
Run Code Online (Sandbox Code Playgroud)

means that the view engine will look for views in this directory: <currentWorkingDirectory>/dist/browser

The current working directory corresponds to the directory where the node process was started from.

So if you want your code to work the same way for local and prod environment (using nginx), you need to make sure that the directory where you start node from is always the parent directory of the dist/browser directory

So you should run node (or pm2) from /var/<project_name>/