Azure虚拟机Node.js API配置HTTPS适配React静态Web应用问题
解决HTTPS React应用无法连接HTTP Node.js API的问题
核心原因
浏览器的混合内容安全限制会阻止HTTPS页面发起HTTP请求,因此必须将Node.js API切换为HTTPS,或通过反向代理实现SSL终止。以下是Azure VM上的完整配置步骤:
1. 开放Azure VM的443端口
- 登录Azure门户,找到目标VM
- 进入「网络」→「入站端口规则」
- 添加规则:端口范围填
443,源选「Any」(或限定信任IP),允许连接
2. 生成免费SSL证书(Let's Encrypt)
在VM终端执行以下命令(以Ubuntu/Debian为例):
- 更新系统包:
sudo apt update && sudo apt install certbot - 生成证书(需提前将域名解析到VM公网IP):
sudo certbot certonly --standalone -d your-domain.com - 证书默认路径:
/etc/letsencrypt/live/your-domain.com/,包含fullchain.pem(证书链)和privkey.pem(私钥)
3. 配置Node.js API支持HTTPS
方案A:直接修改server.js同时支持HTTP/HTTPS
修改你的server.js,引入HTTPS模块并加载证书:
const express = require('express'); const http = require('http'); const https = require('https'); const fs = require('fs'); const dotenv = require('dotenv'); dotenv.config(); const app = express(); // 你的API路由逻辑 app.get('/api/health', (req, res) => { res.status(200).json({ status: 'ok' }); }); // 加载SSL证书 const sslOptions = { key: fs.readFileSync('/etc/letsencrypt/live/your-domain.com/privkey.pem'), cert: fs.readFileSync('/etc/letsencrypt/live/your-domain.com/fullchain.pem') }; // 启动服务 http.createServer(app).listen(process.env.HTTP_PORT || 8080); https.createServer(sslOptions, app).listen(process.env.HTTPS_PORT || 443);
更新.env文件:
HTTP_PORT=8080 HTTPS_PORT=443 NODE_ENV=production
方案B:用Apache反向代理(推荐,同时托管React静态文件)
如果需要同时部署React静态文件,用Apache做反向代理更便捷:
- 安装Apache:
sudo apt install apache2 - 启用必要模块:
sudo a2enmod proxy proxy_http ssl rewrite - 创建虚拟主机配置文件
/etc/apache2/sites-available/your-domain.conf:<VirtualHost *:443> ServerName your-domain.com SSLEngine on SSLCertificateFile /etc/letsencrypt/live/your-domain.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/your-domain.com/privkey.pem # 反向代理到Node.js API(监听8080) ProxyPass /api http://localhost:8080/api ProxyPassReverse /api http://localhost:8080/api # 托管React静态文件(假设文件放在/var/www/react-app) DocumentRoot /var/www/react-app <Directory /var/www/react-app> AllowOverride All Require all granted </Directory> </VirtualHost> # HTTP强制跳转HTTPS <VirtualHost *:80> ServerName your-domain.com Redirect permanent / https://your-domain.com/ </VirtualHost> - 启用站点并重启Apache:
sudo a2ensite your-domain.conf sudo systemctl restart apache2
此方案下,Node.js只需保持监听8080的HTTP服务即可,无需修改HTTPS配置。
4. 用pm2管理Node.js进程
- 如果是方案A,重启pm2进程:
pm2 restart server.js - 推荐用pm2配置文件
ecosystem.config.js统一管理:module.exports = { apps: [{ name: 'node-api', script: './server.js', env: { NODE_ENV: 'production', HTTP_PORT: 8080, HTTPS_PORT: 443 } }] }; - 启动命令:
pm2 start ecosystem.config.js
5. 验证配置
- 测试API:
curl https://your-domain.com/api/health,确认返回正常JSON - 修改React应用的API请求地址为
https://your-domain.com/api/...,避免HTTP请求
内容的提问来源于stack exchange,提问作者The Old County
相关产品推荐
相关产品推荐

