You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express Node.js子域名配置本地正常,部署线上服务器后出现502错误求助

子域名部署问题排查指导

核心问题

  • 本地测试express-subdomain子域名配置正常,但线上部署后Postman返回502 Bad Request
  • 本地使用带IP的子域名URL(如http://api.192.168.86.83:8080/members/login)无法访问

排查步骤

1. 线上502错误(服务器代理层问题)

502错误本质是反向代理(Nginx/Apache)无法正确转发请求到你的Express服务,重点检查:

  • DNS解析:确认api.my-website.net已配置正确的A/CNAME记录,指向服务器公网IP
  • 代理服务器配置:以Nginx为例,需为api子域名单独配置server块,并确保传递原始Host头(否则Express无法识别子域名):
    server {
        server_name api.my-website.net;
        location / {
            proxy_pass http://localhost:8080; # 对应你的Express服务端口
            proxy_set_header Host $host; # 关键:必须保留原始请求的Host
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
    
  • 配置验证:执行nginx -t检查Nginx配置语法,重启代理服务后重试
  • 防火墙/安全组:确认服务器80/443端口(线上默认端口)已开放,且Express服务端口(如8080)允许代理服务器内部访问

2. 子域名校验中间件缺陷

你手动编写的中间件存在逻辑漏洞:

  • 当访问IP形式的子域名时(如api.192.168.86.83),host.split('.')[0]取到api,但IP本身无二级域名结构,会导致逻辑混乱
  • 优化后的中间件(区分域名/IP场景):
    function subdomainRequired(req, res, next) {
      const host = req.headers.host.split(':')[0]; // 剥离端口号
      // 判断是否为IP地址
      const isIp = /^\d+\.\d+\.\d+\.\d+$/.test(host);
      
      if (isIp) {
        // IP访问时可直接放行,或根据需求限制
        return next();
      }
      
      const subdomain = host.split('.')[0];
      if (subdomain === 'api') {
        return next();
      } else {
        res.status(403).send('Access Denied');
      }
    }
    
  • 更推荐用express-subdomain包自带的路由绑定,替代手动校验:
    const subdomain = require('express-subdomain');
    // 直接将api子域名绑定到userRoutes
    app.use(subdomain('api', userRoutes));
    

3. CORS配置语法错误

你的CORS配置存在语法问题,会导致规则失效:

  • origin数组中第一个元素'*'后缺少逗号,引发语法错误
  • 且credentials: true时不能使用'*'作为origin(浏览器会阻止),需明确列出允许的源:
    app.use(cors({
      origin: [
        'http://localhost:3000',
        'http://api.localhost:8080', // 替换为本地实际端口
        'http://api.my-website.net'
      ],
      credentials: true
    }));
    

4. 本地IP子域名访问问题

本地无法通过api.192.168.86.83访问,是因为本地DNS无法解析IP前缀的子域名,解决方法:

  • 修改本地hosts文件:
    • Windows:C:\Windows\System32\drivers\etc\hosts
    • Mac/Linux:/etc/hosts
  • 添加一条记录:
    192.168.86.83 api.localdev
    
  • 使用http://api.localdev:8080/members/login访问即可正常解析子域名

内容的提问来源于stack exchange,提问作者JamimahIB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 12:58:05