简体   繁体   English

如何配置expressjs以在生产模式下提供index.html?

[英]How to configue expressjs to serve index.html in production mode?

I am trying to deploy my app to my local computer to simulate the deployment process. 我正在尝试将我的应用程序部署到本地计算机上,以模拟部署过程。 You call it staging mode or whatever. 您称其为暂存模式。 Tools I used include pm2 and Nginx. 我使用的工具包括pm2和Nginx。

I am able to use my web app when I run my app using pm2 start server.js directly in my project. 当我直接在项目中使用pm2 start server.js运行我的应用程序时,我可以使用我的Web应用程序。 The client can access the index.html file though a Nginx server. 客户端可以通过Nginx服务器访问index.html文件。 But I think this is not production mode unless I also use --env production . 但是我认为这不是生产模式,除非我也使用--env production

So I copy all the required files to the dist directory of my project, configured Nginx to serve the static contents, and in my source code, I want to use 因此,我将所有必需的文件复制到项目的dist目录中,将Nginx配置为提供静态内容,并且在我的源代码中,我想使用

app.get('/', function(req, res) {
    res.sendFile('index.html', {root: somePath});
});

to allow the clients to access the index.html file on express server. 允许客户端访问Express服务器上的index.html文件。 But I am not sure what to put in somePath ? 但是我不确定在somePath放什么? I separate the server side and client side when I deploy my project to the server. 将项目部署到服务器时,我将服务器端和客户端分开。 For example, my server side is on /usr/path/server but my client side is on /etc/shared/html . 例如,我的服务器端在/usr/path/server而我的客户端在/etc/shared/html If I mess up with the paths I will get a "forbidden" error message from express when I access index.html . 如果弄乱了路径,当我访问index.html时,我将从express收到“禁止”错误消息。

If you want make production-like repeatability during development, then you should implement same functionality with same tools. 如果要在开发过程中实现类似生产的可重复性,则应使用相同的工具实现相同的功能。

Nowadays docker compose is best solution for resolve this issue. 如今, docker compose是解决此问题的最佳解决方案。 As start you should have two container the first with nginx and the second with pm2. 首先,您应该有两个容器,第一个包含nginx,第二个包含pm2。 Also you should bind/mount volume for static files to nginx. 另外,您应该将静态文件的卷绑定/挂载到nginx。

Your code should be like this. 您的代码应如下所示。

 var path = require('path');
 var virtualDirPath = process.env.virtualDirPath || '';
 var appDir = path.dirname(require.main.filename) + virtualDirPath;

appDir will give the environment directory , from where you can access the html file. appDir将提供环境目录 ,从中可以访问html文件。

Hope it helps:) 希望能帮助到你:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM