title: Socket-Management in Nginx with Flask - Why is Cross-Origin Request Blocked?
body: <p>I want to create a socket in Flask-SocketIO through Nginx and Unicorn. The following configuration works on <em>localhost</em> without Nginx.</p>
  
  <p>When I access the web application through Nginx in Chrome, i get the error:</p>
  
  <blockquote>
    <p>Failed to load resource: Could not connect to the server.
    <a href="http://52.34.18.48:6419/socket.io/?EIO=3&amp;transport=polling&amp;t=1454455363683-6" rel="nofollow">http://52.34.18.48:6419/socket.io/?EIO=3&amp;transport=polling&amp;t=1454455363683-6</a></p>
  </blockquote>
  
  <p>When I access the web application through Nginx in Firefox, I get the error:</p>
  
  <blockquote>
    <p>Cross-Origin Request Blocked: The Same Origin Policy disallows reading
    the remote resource at
    <a href="http://52.34.18.48:6419/socket.io/?EIO=3&amp;transport=polling&amp;t=1454464333740-25" rel="nofollow">http://52.34.18.48:6419/socket.io/?EIO=3&amp;transport=polling&amp;t=1454464333740-25</a>. (Reason: CORS request failed).</p>
  </blockquote>
  
  <p>This is how I initialize the socket connection in JavaScript:</p>
  
  <pre><code>import io from "socket.io-client"
  
  const socketUrl = 'http://' + document.domain + ':6419' + '/FlaskApp'
  const socket = io(socketUrl);
  
  export default socket;
  </code></pre>
  
  <p>My Nginx config file looks like this:</p>
  
  <pre><code>server {
      listen 80;
      server_name 52.34.18.48;
      error_log /var/www/Flaskapp/nginx_errorlog.log;
      access_log /var/www/Flaskapp/nginx_accesslog.log;
  
      root /var/www/Flaskapp;
  
      location /socket.io {
          proxy_pass http://127.0.0.1:6419/socket.io;
          proxy_redirect off;
          proxy_buffering off;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP  $remote_addr;
          proxy_set_header X-Forwarded-For $remote_addr;
  
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
      }
  
      location / {
          proxy_pass http://127.0.0.1:6419;
          proxy_buffering off;
          proxy_set_header X-Real-IP  $remote_addr;
          proxy_set_header X-Forwarded-For $remote_addr;
          proxy_set_header Host $host;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
      }
  </code></pre>
  
  <p>The Gunicorn command I used is:</p>
  
  <pre><code>gunicorn --worker-class eventlet -w 1 -b 127.0.0.1:6419 flask_app:application
  </code></pre>
  
  <p>I wrapped the socket in the Flask application like this.</p>
  
  <pre><code>from flask_app import application
  from flask_socketio import SocketIO
  
  socketio = SocketIO(application)
  </code></pre>
  
  <p>Why do I get this error via Nginx but not when connecting via localhost? How can I access the socket.io via Nginx correctly?</p>