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

Sails+Socket.IO+Nginx架构下的CORS问题排查与解决求助

Fixing CORS Issues in Your Sails + Socket.IO + Nginx Setup

Hey there, let's work through this CORS problem you're facing with your stack. I've debugged similar setups before, so let's break down the key areas to check and fix:

1. Configure Sails.js CORS Properly

Sails has built-in CORS settings that need to align with your frontend and Nginx setup—especially for Socket.IO, which handles both HTTP polling and WebSocket connections.

  • Open your Sails config/cors.js file and update these settings:
    module.exports.cors = {
      origin: '*', // Replace with your frontend's actual domain (e.g., 'https://your-frontend.com') for production
      credentials: true, // Enable this if your frontend sends cookies/auth headers
      methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
      headers: 'Content-Type, Authorization, X-Requested-With',
      exposeHeaders: ''
    };
    
  • For Socket.IO-specific adjustments, check config/sockets.js (or config/http.js in newer Sails versions) to ensure the server accepts cross-origin connections. You can add an allowRequest handler if needed:
    module.exports.sockets = {
      allowRequest: function(req, callback) {
        // Allow all cross-origin requests (tighten this for production)
        callback(null, true);
      }
    };
    

2. Update Nginx Reverse Proxy Configuration

Nginx acts as the gateway, so it needs to properly forward CORS headers and handle Socket.IO's WebSocket handshake. Here's the corrected location block for your /node/ prefix:

location /node/ {
    proxy_pass http://localhost:3000/;
    # Basic proxy headers to preserve client info
    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;

    # CORS headers - dynamically match the client's origin
    add_header Access-Control-Allow-Origin $http_origin always;
    add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
    add_header Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With" always;
    add_header Access-Control-Allow-Credentials "true" always;

    # Handle preflight OPTIONS requests directly (no need to forward to Sails)
    if ($request_method = OPTIONS) {
        return 204;
    }

    # Critical for Socket.IO/WebSocket support
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 86400; # Prevent timeout for long-lived WebSocket connections
}
  • The always keyword ensures CORS headers are sent even for error responses.
  • The WebSocket-related headers (Upgrade, Connection) are mandatory for Socket.IO to work correctly across domains.

3. Adjust Socket.IO Client Settings

Make sure your frontend client connects through Nginx and sends credentials if needed:

import { io } from 'socket.io-client';

// Connect to the Nginx-proxied endpoint
const socket = io('https://your-domain.com/node', {
    withCredentials: true, // Match Sails' credentials setting
    transports: ['websocket', 'polling'], // Prioritize WebSocket to avoid polling CORS issues
    reconnection: true
});

4. Verify the Fix

  • Open your browser's DevTools > Network tab.
  • Check that the Access-Control-Allow-Origin header in responses matches your frontend's origin.
  • Ensure OPTIONS preflight requests return a 204 status code.
  • Look for Socket.IO's handshake requests (path like /node/socket.io/?EIO=4...) and confirm they don't throw CORS errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:11:53