本地部署LiveSmart Server Video遇Apache与Node.js协作故障求助
解决方案:Apache与Node.js协同处理请求(解决404与跨域问题)
方案一:Node.js反向代理PHP请求至Apache
保持Node服务(9002端口)作为前端入口,将PHP请求转发给Apache处理:
- 安装代理依赖:在项目根目录运行
npm install http-proxy-middleware --save - 找到Node服务的启动文件(如
server.js或app.js),添加代理规则:const { createProxyMiddleware } = require('http-proxy-middleware'); // 转发所有/server开头的请求到Apache的项目路径 app.use('/server', createProxyMiddleware({ target: 'http://localhost/livesmart_server_video/public', changeOrigin: true, pathRewrite: { '^/server': '/server' } })); - 重启Node服务,此时
http://localhost:9002/server/script.php会被转发到Apache处理,404和跨域问题同时解决。
方案二:Apache作为主入口反向代理Node.js请求(推荐)
统一请求入口,彻底避免跨域问题,更贴合生产环境部署逻辑:
- 配置Apache虚拟主机:进入Laragon安装目录,打开
apache\conf\sites-enabled,创建或编辑虚拟主机文件(如livesmart.test.conf),添加以下内容:<VirtualHost *:80> ServerName livesmart.test DocumentRoot "C:\laragon\www\livesmart_server_video\public" # 替换为你的项目public目录实际路径 # 让Apache处理PHP文件 <FilesMatch \.php$> SetHandler "proxy:fcgi://127.0.0.1:9000" # Laragon默认PHP-FPM端口为9000 </FilesMatch> # 将Node相关请求(如socket、前端渲染)转发到9002端口 ProxyPass /socket.io http://localhost:9002/socket.io ProxyPassReverse /socket.io http://localhost:9002/socket.io # 若前端页面由Node渲染,可添加以下两行转发根路径请求 # ProxyPass / http://localhost:9002/ # ProxyPassReverse / http://localhost:9002/ # 允许静态文件访问 <Directory "C:\laragon\www\livesmart_server_video\public"> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> </VirtualHost> - 修改Windows hosts文件:打开
C:\Windows\System32\drivers\etc\hosts,添加一行127.0.0.1 livesmart.test - 重启Laragon的Apache服务,保持Node服务(9002端口)运行
- 访问
http://livesmart.test即可,Apache自动处理PHP请求,Node服务处理对应业务,无跨域问题。
临时跨域解决方案(仅用于测试)
若仅需临时测试,可在Apache中添加CORS头部:
- 在项目public目录下的
.htaccess文件中添加:Header set Access-Control-Allow-Origin "http://localhost:9002" Header set Access-Control-Allow-Methods "GET, POST, OPTIONS" Header set Access-Control-Allow-Headers "Content-Type" - 重启Apache后,直接访问
http://localhost/livesmart_server_video/public/server/script.php不会触发跨域错误,但此方案不适合长期使用。
内容的提问来源于stack exchange,提问作者Jass
相关产品推荐
相关产品推荐

