Angular Universal部署后无法找到main.js与polyfills.js的问题求助
Angular Universal 部署后页面显示异常排查方案
已知信息
- 本地运行正常,部署到服务器后出现异常,怀疑是服务器配置问题
- 部署执行步骤:
1) ng build --configuration production –aot 2) npm run build:ssr 3) Upload the files to the correct folders 4) pm2 kill 5) sudo pm2 start /var/www/myApp.com/html/server/ecosystem.config.js 6) pm2 startup systemd 7) systemctl restart nginx - 项目
index.html内容:<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Something</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="manifest" href="manifest.webmanifest"> <meta name="theme-color" content="#1976d2"> <meta name="description" content="something"> <meta name="keywords" content="something"> <meta name="google-site-verification" content="6xXxEb-Y" /> <meta name="google-site-verification" content="O_PI" /> </head> <body> <app-root></app-root> <noscript>Please enable JavaScript to continue using this application.</noscript> </body> <script src="https://www.youtube.com/iframe_api"></script> <script type="text/javascript" charset="UTF-8" src="something.js"></script> </html> - Nginx配置关联现象:
- 未注释某绿色行:页面源码中
<app-root>标签内容为空 - 注释该行后:
<app-root>内容正常,但网站仍显示不全
- 未注释某绿色行:页面源码中
排查步骤
1. 确认SSR服务运行状态
- 执行以下命令检查pm2管理的SSR进程:
查看日志中是否有端口占用、依赖缺失、文件路径错误等报错信息。pm2 list pm2 logs <你的应用名称> - 直接在服务器本地请求SSR服务端口(假设端口为4000),验证服务本身是否正常返回渲染内容:
检查返回的HTML中curl http://localhost:4000<app-root>是否包含渲染后的内容。
2. 修正Nginx配置逻辑
你提到的绿色行大概率是直接返回本地静态index.html的规则(如try_files $uri $uri/ /index.html;),未注释时Nginx跳过SSR服务直接返回空壳静态页面,导致<app-root>为空;注释后请求转发到SSR,但页面显示不全需要确保Nginx同时正确托管静态资源并转发动态请求:
server { listen 80; server_name myApp.com; # 指定静态资源根目录 root /var/www/myApp.com/html/browser; index index.html; # 托管静态资源(js/css/图片等),设置缓存 location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { expires 1y; add_header Cache-Control "public, immutable"; } # 所有非静态资源请求转发到SSR服务 location / { proxy_pass http://localhost:4000; # 替换为你的SSR服务实际端口 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_cache_bypass $http_upgrade; } }
3. 验证静态资源加载状态
打开浏览器开发者工具(F12),切换到Network标签:
- 检查所有js、css、图片资源是否返回200状态,有没有404错误
- 确认你引入的
something.js是否存在于browser目录下,路径是否正确
4. 检查构建文件与部署路径
- 确认
npm run build:ssr生成的server目录(含main.js、ecosystem.config.js)和browser目录(静态资源)是否完整上传到服务器对应路径 - 检查
ecosystem.config.js中的配置,确保cwd指向正确的server目录,script指向main.js:module.exports = { apps: [{ name: 'my-ssr-app', script: './main.js', cwd: '/var/www/myApp.com/html/server', instances: 1, autorestart: true, watch: false, max_memory_restart: '1G', env: { NODE_ENV: 'production' } }] };
5. 检查服务器权限
执行以下命令查看目录权限,确保pm2运行用户(通常是www-data或你的登录用户)拥有读取项目文件的权限:
ls -l /var/www/myApp.com/html
内容的提问来源于stack exchange,提问作者Paria p
相关产品推荐
相关产品推荐

