Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error during WebSocket handshake: Unexpected response code: 400 #1942

Closed
shi-yuan opened this issue Jan 14, 2015 · 134 comments
Closed

Error during WebSocket handshake: Unexpected response code: 400 #1942

shi-yuan opened this issue Jan 14, 2015 · 134 comments

Comments

@shi-yuan
Copy link

Can't find out a solution, I get this error on the browser console:
WebSocket connection to 'ws://.../socket.io/?EIO=2&transport=websocket&sid=p3af7ZNfvogtq6tAAAG0' failed: Error during WebSocket handshake: Unexpected response code: 400.

Hava any advice ?

@arnauddri
Copy link

I am experiencing the exact same issue at the moment, any help?

@vhf
Copy link

vhf commented Jan 19, 2015

I am also having this issue since I installed a SSL cert on my domain.

Here is a better description of the issue: http://stackoverflow.com/questions/28025073/error-during-websocket-handshake-unexpected-response-code-400-with-nginx-proxy

@KieranWebber
Copy link

Im also having a similar issue connecting with with one of the Android library's. Web sockets won't connect to https through either HAproxy doing ssl termination or letting node do ssl directly. Long polling works fine however

@shi-yuan
Copy link
Author

I resolve it by changing the domain to the true IP address:

var socket = io.connect('http://182.92.79.215:3007');

@tylercb
Copy link

tylercb commented Mar 17, 2015

Had the same issue, my app is behind nginx. Making these changes to my Nginx config removed the error.

location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}

This is originally from https://chrislea.com/2013/02/23/proxying-websockets-with-nginx/

@mikedavies-dev
Copy link

Same issue here on production server. Development machines do not show the error.

The strange thing is that the connection is working. I can send messages via WebSockets from the server and the client gets them. I can also see the WebSocket connection being established on the server.

I just get this error in developer tools saying:

WebSocket connection to 'wss://.../socket.io/?EIO=3&transport=websocket&sid=2b_v_BXtbwzl5z2yAAAI' failed: Error during WebSocket handshake: Unexpected response code: 400

I'm using Apache ProxyPass to send connections to node.

@CaptainCannabis
Copy link

Same here - full functional but Error message in dev tools. Somewhere else i read its related to the apache version - using 2.2.14 on this machine.

@rickyk586
Copy link

Make sure you're socket.io connection isn't going through an Amazon Load Balancer. Or if so, do this: http://blog.flux7.com/web-apps-websockets-with-aws-elastic-load-balancing

@napcoder
Copy link

Same issue here, only in production environment.
Websockets seems to work correctly, the application works without problems. But on console log I can see this error.

I'm using Nginx and only one server for node, so it seems to be not a load balancing problem. I was already using the solution suggested by tylercb (with the exception of "proxy_set_header Host $host;") and it is not solving the issue.

@zscorpio
Copy link

also have problem ,but work well....

@spinda
Copy link

spinda commented Apr 28, 2015

I had this same issue. Are you using CloudFlare? Currently, only their Enterprise plan supports WebSockets.

@napcoder
Copy link

Solved for me. It was due to wrong socket.io address in nginx configuration, that was not matching the path using the websocket.

@rudolfschmidt
Copy link

I googled because I got the same problem and I also use nginx. The solution is to add this part

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;

into the nginx configuration file like tylercb mentioned.

@capr
Copy link

capr commented May 17, 2015

Worked for me. Thanks.

@burmisov
Copy link

Got same error directly connecting to my app hosted on Windows Server 2008R2 (no proxy, no IIS). Only dumb intermediate hardware in between.

@ghost
Copy link

ghost commented Jun 15, 2015

Work fine after switched host name to ip address, i.e. 127.0.0.1:9000. may caused by httpd ProxyPassReverse

@nanyaks
Copy link

nanyaks commented Aug 9, 2015

In my case, the issue was as a result of cloudfare not supporting websockets on the free plan. I turned off CloudFare for the domain and it worked.

@cpres
Copy link

cpres commented Sep 30, 2015

I just needed to add some Apache rewrite conditions to handle the websockets, more info here:
http://stackoverflow.com/a/27534443/2044993

@alexrosenfeld
Copy link

I know this is an old issue, but since it's high on Google search results, but this might help people:

The reason the connection still works even with this error is that socket.io is falling back to AJAX, which is not optimal and you should fix your server configuration.

Btw, this issue should remain closed, it's not a socket.io issue.

@cgodkin
Copy link

cgodkin commented Dec 17, 2015

@arosenfeld-mentel I keep reading the posts above your comment that "this is not a socket.io issue" but I don't see where anyone says WHAT the issue actually is. I see this myself although, as you say, the connection still seems to work. Any tips would be very gratefully received. Thanks!

@alexrosenfeld
Copy link

The issue could be anything really, you need to debug your whole setup. For me it was NGINX, which as reverse proxy needs the additional configuration settings posted above many times. For you could be something else.

Start by debugging the local connection, get it to work without the warning, then move to the production server and make sure you get firewalls, front-facing servers and proxys to cooperate with WebSockets.

It's not a socket.io issue, but it is a WebSockets issue, so make sure the server and the client works well with WebSockets.

@e1016
Copy link

e1016 commented Nov 26, 2019

Create manual instance (without express app instance) and assign a different port

const io = require('socket.io')(3001, {
  path: '/',
  serveClient: false,
  // below are engine.IO options
  pingInterval: 10000,
  pingTimeout: 5000,
  cookie: false
})

@EduardsE
Copy link

Had the same issue, my app is behind nginx. Making these changes to my Nginx config removed the error.

location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}

This is originally from https://chrislea.com/2013/02/23/proxying-websockets-with-nginx/

I was missing proxy_set_header Connection "upgrade";

@yingshaoxo
Copy link

yingshaoxo commented Jan 26, 2020

I've been spending a whole night to solve this problem when I start to use https or wss or ssl. It always says connection stopped before establish with 400 error code.

Just a minutes ago, I found a solution for that:

0. Cloudflare

At the SSL/TLS tab:

  • If you have your own cert or SSL or HTTPS: set it to Full. (The following 123 steps assume you have your own https certification)

  • If you only have an http server: set it to Flexible. (The Cloudflare will add https or ssl to your website automatically.)

  • After that, go to DNS tab, set Proxied.

If you are not sure what you are doing, just go to DNS tab, set DNS only

1. Make sure you have a right proxy configuration.

server {
    listen 80;
    server_name ai-tools-online.xyz;
    return 301 https://ai-tools-online.xyz$request_uri;
}

server {
    listen 443 ssl http2;

    ssl_certificate       /data/v2ray.crt;
    ssl_certificate_key   /data/v2ray.key;
    ssl_protocols         TLSv1.2 TLSv1.3;
    #ssl_ciphers           3DES:RSA+3DES:!MD5;
    server_name ai-tools-online.xyz;

    location / {
        proxy_pass http://127.0.0.1:5000;
    }

    location /socket.io {
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_pass http://127.0.0.1:5000/socket.io;
    }
}

ai-tools-online.xyz is your domain, http://127.0.0.1:5000 is your socket server.

2. Make sure your server Cross-Origin Controls is set to '*' to allow Cross-Origin Access

For flask-socketio, is to use flask_socketio.SocketIO(app, cors_allowed_origins = '*')

3. You must restart the nginx to let the new config work

systemctl restart nginx

4. For more details about how to set caddy, see the following links:

https://github.com/yingshaoxo/Web-Math-Chat#reverse-proxy-configuration-for-https
https://caddy.community/t/using-caddy-0-9-1-with-socket-io-and-flask-socket-io/508/6
https://www.nginx.com/blog/nginx-nodejs-websockets-socketio/

@debaosuidecl
Copy link

I googled because I got the same problem and I also use nginx. The solution is to add this part

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;

into the nginx configuration file like tylercb mentioned.

worked for me well thank you !

@flyingabhijeet
Copy link

If you are using Elastic Beanstalk just like me to create node-server,
While creating the environment we are being asked in configurations to use which Proxy Server. In which nginx is pre-populated or default set.
I set that proxy server to none and then continued to continue creating my server. I was using Elastic Beanstalk to create a node server in which my proxy server was default set to nginx.
As it is an error of configuring proxy server. After removing any proxy server, the error disappeared.

@luigimannoni
Copy link

luigimannoni commented Feb 13, 2020

Been googling for hours and none of the solutions above applied to us since we just had a nodejs app and no nginx.

The way we solved this was just to disable nginx from the container -> load balancer settings to pass all traffic directly to node.

@cacothi
Copy link

cacothi commented Mar 20, 2020

Been googling for hours and none of the solutions above applied to us since we just had a nodejs app and no nginx.

The way we solved this was just to disable nginx from the container -> load balancer settings to pass all traffic directly to node.

how did you do that?

@luigimannoni
Copy link

luigimannoni commented Mar 20, 2020

If you go to Configuration > Load balancer you can find a drop-down for the proxy server, you can use nginx, Apache or set it to "none" to pass through all connections to the node app.

This only appears if you create an environment with a load balancer, doesn't work for single instances

Edit: my original comment was referred to Elastic Beanstalk

@NazimMertBilgi
Copy link

Had the same issue, my app is behind nginx. Making these changes to my Nginx config removed the error.

location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}

This is originally from https://chrislea.com/2013/02/23/proxying-websockets-with-nginx/

So so thank youuu.

@theavuthnhel
Copy link

This document is for those who use laravel-echo-server & Nginx & socket.io & Redis-server with the separated server between client project and Redis-server.

Please follow the link here.

Thanks

@vankeer
Copy link

vankeer commented Apr 10, 2020

I had this issue. Updating my nginx config didn't help, but @santhosh77h 's solution fixed it for me. For some reason passing the array of allowed origins doesn't work, but using the callback does.

I use Nest.js websockets (just a wrapper around Socket.io) and added the following to my gateway:

afterInit(server: Server): any {
    const origins = getOrigins(); // returns an array of origin strings
    server.origins((origin, cb) => {
      if (origins.includes(origin)) {
        cb(null, true)
      } else {
        cb('Invalid origin', false);
      }
    });
  }

@jakubsuplicki
Copy link

jakubsuplicki commented Apr 15, 2020

I had the same issue with NUXT.js with Node.js / Express running on AWS Elastic Beanstalk (Nginx proxy). Took me a few days to figure this out. I'll share my reading points. Maybe someone will find it useful.

My environment is on Application Load Balancer with two ports 80 for https and 443 for https with SSL.

In the combination of the answer from above, big thanks to @tylercb and official documentation from AWS and socket.io documentation I created an Nginx config file that seems to be fixing the issue.

I will quickly outline the steps:

In my index.js Node file:

const express = require('express')
const app = express()
const server = http.createServer(app)
const io = require('socket.io')(server)
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 8081

On the front-end (one of my components):
import io from 'socket.io-client';
in my Vue data():
socket: io()

Finally, In the application root, I created a folder .ebextensions
Right inside I created a file 01-proxy.config with the following content:

files:
  /etc/nginx/conf.d/01-proxy.conf:
     mode: "000644"
     owner: root
     group: root
     content: |
        upstream nodejs {
          server 127.0.0.1:8081;
          keepalive 256;
        }
        server {
          listen 8080;
          server_name yourdomain.com;

          if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") {
            set $year $1;
            set $month $2;
            set $day $3;
            set $hour $4;
          }
          access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd;
          access_log  /var/log/nginx/access.log  main;

          location / {
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header Host $host;

              proxy_pass http://nodejs;

              proxy_http_version 1.1;
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection "upgrade";
          }

          gzip on;
          gzip_comp_level 4;
          gzip_types text/html text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

          location /static {
              alias /var/app/current/static;
          }

        }
       
  /opt/elasticbeanstalk/hooks/configdeploy/post/99_kill_default_nginx.sh:
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/bin/bash -xe
      rm -f /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf
      service nginx stop 
      service nginx start

container_commands:
  removeconfig:
    command: "rm -f /tmp/deployment/config/#etc#nginx#conf.d#00_elastic_beanstalk_proxy.conf /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf"

Additional readings:
nginx configuration

That's it. Quite lengthy. My apologies and good luck.

@knarasimhar
Copy link

working for me below change in ubuntu and ngnix server for angular .net core

location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}

@nighttiger1990
Copy link

If anyone still having problems using Nodejs + Express, maybe your problem could be express-status-monitor, as @slaveofcode mentioned. As sated in its NPM documentation, this module spawn its own socket.io instance, so you should fill websocket parameter with your main socket.io instance, as well port parameter:

const io = require('socket.io')(server);
const expressStatusMonitor = require('express-status-monitor');
app.use(expressStatusMonitor({
  websocket: io,
  port: app.get('port')
}));

This info helped me

@LeonardoRick
Copy link

Make sure you're socket.io connection isn't going through an Amazon Load Balancer. Or if so, do this: http://blog.flux7.com/web-apps-websockets-with-aws-elastic-load-balancing

If someone else had this issue using AWS load balancer, The article metioned doesn't say that it's possible too to use SSL as load balancer protocol and keep using your certificate on this configuration, out of you app server level.

This is how my LB listeners looks like

image

Worked well for me!

@makaderbd
Copy link

Had the same issue, my app is behind nginx. Making these changes to my Nginx config removed the error.

location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}

This is originally from https://chrislea.com/2013/02/23/proxying-websockets-with-nginx/

Yes. This was help-ful and worked for me as well.

@andressspinetti
Copy link

Make sure you're socket.io connection isn't going through an Amazon Load Balancer. Or if so, do this: http://blog.flux7.com/web-apps-websockets-with-aws-elastic-load-balancing

If someone else had this issue using AWS load balancer, The article metioned doesn't say that it's possible too to use SSL as load balancer protocol and keep using your certificate on this configuration, out of you app server level.

This is how my LB listeners looks like

image

Worked well for me!

Nice, it worked.

@victorsferreira
Copy link

Make sure you're socket.io connection isn't going through an Amazon Load Balancer. Or if so, do this: http://blog.flux7.com/web-apps-websockets-with-aws-elastic-load-balancing

If someone else had this issue using AWS load balancer, The article metioned doesn't say that it's possible too to use SSL as load balancer protocol and keep using your certificate on this configuration, out of you app server level.

This is how my LB listeners looks like

image

Worked well for me!

in this case your application is running on 80?

@mjsaijem09
Copy link

Here

Page not found

@helloalvin
Copy link

我同样遇到了这个问题,我是wx小程序端+flask socketio,
后面设置SocketIO 的cors_allowed_origins='*' 解决了 400问题。

@codeyourwayup
Copy link

location /{
// your regular http config is here
}

location /socket.io {
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass http://127.0.0.1:5000/socket.io;
}


Above works form me!!

@dev-improving
Copy link

Had the same issue, my app is behind nginx. Making these changes to my Nginx config removed the error.

location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}

This is originally from https://chrislea.com/2013/02/23/proxying-websockets-with-nginx/

It works!!!!
Now the thing is... how you figured out? XD

@darrachequesne
Copy link
Member

For future readers, this issue is most certainly due to either:

  • a wrong configuration of a reverse proxy in front of your Socket.IO server

Please check the documentation here: https://socket.io/docs/v4/reverse-proxy/

  • the lack of sticky session, in case you are using several Socket.IO servers

Please check the documentation here: https://socket.io/docs/v4/using-multiple-nodes/

And finally: https://socket.io/docs/v4/troubleshooting-connection-issues/

@socketio socketio locked as resolved and limited conversation to collaborators Sep 23, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests