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 · 128 comments
Closed

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

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

Comments

@shi-yuan
Copy link

@shi-yuan shi-yuan commented Jan 14, 2015

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

@arnauddri arnauddri commented Jan 14, 2015

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

@vhf
Copy link

@vhf 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

@KieranWebber KieranWebber commented Jan 19, 2015

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 shi-yuan closed this Jan 26, 2015
@shi-yuan
Copy link
Author

@shi-yuan shi-yuan commented Jan 26, 2015

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 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/

@ant-fx
Copy link

@ant-fx ant-fx commented Apr 9, 2015

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

@CaptainCannabis CaptainCannabis commented Apr 14, 2015

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

@rickyk586 rickyk586 commented Apr 19, 2015

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

@napcoder napcoder commented Apr 24, 2015

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

@zscorpio zscorpio commented Apr 28, 2015

also have problem ,but work well....

@spinda
Copy link

@spinda spinda commented Apr 28, 2015

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

@napcoder
Copy link

@napcoder napcoder commented Apr 28, 2015

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

@rudolfschmidt rudolfschmidt commented May 6, 2015

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 capr commented May 17, 2015

Worked for me. Thanks.

@burmisov
Copy link

@burmisov burmisov commented May 25, 2015

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

@sunnymix
Copy link

@sunnymix sunnymix 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 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 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

@alexrosenfeld alexrosenfeld commented Dec 16, 2015

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 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

@alexrosenfeld alexrosenfeld commented Dec 17, 2015

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.

@knifesk
Copy link

@knifesk knifesk commented Jul 9, 2019

This is my Apache config, notice it's using a /ws/ path prefix, but otherwise it works fine.

    ProxyRequests Off
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    RewriteEngine On
    RewriteCond %{REQUEST_URI}  ^/ws/socket.io         [NC]
    RewriteCond %{QUERY_STRING} transport=websocket    [NC]
    RewriteRule /ws/(.*)           ws://localhost:6001/$1 [P,L]
    ProxyPass /ws http://127.0.0.1:6001
    ProxyPassReverse /ws http://127.0.0.1:6001
@oceaneLonneux
Copy link

@oceaneLonneux oceaneLonneux commented Aug 22, 2019

Currently facing this issue with exposing the Linkerd dashboard (service mesh) for our EKS cluster. we use nginx, so not exactly sure how to get out of that one at this moment.

@Ancinek
Copy link

@Ancinek Ancinek commented Aug 28, 2019

@andrzj OMG man, you just saved me.

@Kevinlinpr
Copy link

@Kevinlinpr Kevinlinpr commented Sep 21, 2019

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.

@nikodunk
Copy link

@nikodunk nikodunk commented Oct 7, 2019

Thanks for the help gang! If anyone is trying to get this working next to normal HTTPS traffic, it's now working on Elastic Beanstalk for me with the following settings:

  • On Elastic Beanstalk: nginx turned off (for now, haven't got round to trying the above config yet).
  • On Elastic Beanstalk: Load balancer as follows:
  • On Node/Express: const io = require('socket.io')(3030)
  • On client simply naming let connection = io(https://www.myurl.com:3030)
@santhosh77h
Copy link

@santhosh77h santhosh77h commented Oct 22, 2019

If you guys are still having this issue and you have set allowed origin in socket server as array or origins instead of callback function to filter origins would throw this error

Error during WebSocket handshake: Unexpected response code: 400

In my case updating this logic

io.origins(['https://foo.example.com:443']);

to this

io.origins((origin, callback) => {  
     if (origin !== 'https://foo.example.com') {    
         return callback('origin not allowed', false);  
     }  
    callback(null, true);
});

Worked without any errors thrown.

@ecda909
Copy link

@ecda909 ecda909 commented Nov 6, 2019

Getting this same error, but I added in the configs for NGINX and I am still receiving the same 400 handshake error. I am however, using an Application Load Balancer in AWS and I have it set to an :80 Target Group and a 443 listener which forwards to the Target Group.

NGINX conf file:

`server {

listen [::]:80;
listen 80;

server_name <domain_name>;
access_log  /var/log/nginx/access.log;

location / {
    proxy_pass http://127.0.0.1:8000;
    include proxy_params;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
}

location /socket.io {
    include proxy_params;
    proxy_http_version 1.1;
    proxy_cache_bypass $http_upgrade;
    proxy_buffering off;
    proxy_set_header Host $host;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_pass http://127.0.0.1:8000;
}

}`

And within my js file I have a connection for socket.io that looks like this:
var socket = io()

@e1016
Copy link

@e1016 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

@EduardsE EduardsE commented Dec 25, 2019

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 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

@debaosuidecl debaosuidecl commented Jan 29, 2020

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

@flyingabhijeet flyingabhijeet commented Feb 13, 2020

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 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 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 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

@NazimMertBilgi NazimMertBilgi commented Mar 30, 2020

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

@theavuthnhel theavuthnhel commented Apr 10, 2020

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 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 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

@knarasimhar knarasimhar commented Apr 25, 2020

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

@nighttiger1990 nighttiger1990 commented Aug 3, 2020

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

@LeonardoRick LeonardoRick commented Aug 29, 2020

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

@makaderbd makaderbd commented Sep 23, 2020

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

@andressspinetti andressspinetti commented Sep 23, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
You can’t perform that action at this time.