Websocket connection to wss failed error during websocket handshake unexpected response code 400

I use socket.io in my node.js app that's running on express. Everything words fine on the local version (localhost) however when I switch to my production server (which is served via https using a ...

I use socket.io in my node.js app that’s running on express.

Everything words fine on the local version (localhost) however when I switch to my production server (which is served via https using a custom certificate), I get the following error in my browser console:

websocket.js:112 WebSocket connection to 'wss://infranodus.com/socket.io/?EIO=3&transport=websocket&sid=j_WBxkPY_RlpF9_ZAANP' failed: Error during WebSocket handshake: Unexpected response code: 400

I made a research (issue referenced here) and it turns out this happens because my app / hosting provider blocks connections like wss and my socket.io falls back on AJAX to make requests (which functions OK, but sometimes there are bugs).

So I wanted to ask you if I could do modifications to my app to get rid of this error?

Just FYI currently all requests to http://infranodus.com are forwarded (via static .htaccess) to https://infranodus.com and my app.js file (the part of the server activation looks like that):

var http = require('http');

var app = express();

var server = http.Server(app);
var io = require('socket.io')(server);

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

and the way I require sockets in my front-end file:

<script src="/socket.io/socket.io.js"></script>

and then

var socket = io();

Maybe the problem is that I activate server in my node.js app using http and not https? But I would not like to switch to that because I don’t know where my certificates are stored and I would not like to change the backend code too much.

UPDATE (21/10/2018): We figured out the problem is with nginx server and due to the limitations of some hosting providers who do not allow users to edit nginx servers, websockets over secure protocol get blocked or get 400 error. It would be nice to resolve this in sockets.io as it’s a problem that many users have. Any ideas?

TO REPRODUCE THE ISSUE: Please, go open your Javascript Console and go to https://infranodus.com/news/english

SOURCE CODE: https://github.com/noduslabs/infranodus

I use socket.io in my node.js app that’s running on express.

Everything words fine on the local version (localhost) however when I switch to my production server (which is served via https using a custom certificate), I get the following error in my browser console:

websocket.js:112 WebSocket connection to 'wss://infranodus.com/socket.io/?EIO=3&transport=websocket&sid=j_WBxkPY_RlpF9_ZAANP' failed: Error during WebSocket handshake: Unexpected response code: 400

I made a research (issue referenced here) and it turns out this happens because my app / hosting provider blocks connections like wss and my socket.io falls back on AJAX to make requests (which functions OK, but sometimes there are bugs).

So I wanted to ask you if I could do modifications to my app to get rid of this error?

Just FYI currently all requests to http://infranodus.com are forwarded (via static .htaccess) to https://infranodus.com and my app.js file (the part of the server activation looks like that):

var http = require('http');

var app = express();

var server = http.Server(app);
var io = require('socket.io')(server);

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

and the way I require sockets in my front-end file:

<script src="/socket.io/socket.io.js"></script>

and then

var socket = io();

Maybe the problem is that I activate server in my node.js app using http and not https? But I would not like to switch to that because I don’t know where my certificates are stored and I would not like to change the backend code too much.

UPDATE (21/10/2018): We figured out the problem is with nginx server and due to the limitations of some hosting providers who do not allow users to edit nginx servers, websockets over secure protocol get blocked or get 400 error. It would be nice to resolve this in sockets.io as it’s a problem that many users have. Any ideas?

TO REPRODUCE THE ISSUE: Please, go open your Javascript Console and go to https://infranodus.com/news/english

SOURCE CODE: https://github.com/noduslabs/infranodus

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.

Содержание

  1. WebSocket connection to ‘ws://localhost:4000/’ failed: Error during WebSocket handshake: Unexpected response code: 400 #4778
  2. Comments
  3. Устранение ошибок подключения
  4. Код ответа 404
  5. Код ответа 400 или 503
  6. Код ответа 307
  7. Код ответа 405
  8. Код ответа 0
  9. Код ответа 413
  10. Временные сбои сети
  11. WebSocket handshake: Unexpected response code: 400 #468
  12. Comments
  13. Description
  14. Related Issues
  15. Description
  16. Related Issues
  17. Description
  18. Related Issues
  19. Footer
  20. WebSocket connection to ‘wss://api-such.andsuch.xyz/graphql/’ failed: Error during WebSocket handshake: Unexpected response code: 400
  21. Popular Topics
  22. Questions
  23. Welcome to the developer cloud
  24. Проблема чего: «Ожидание доступного сокета»?

WebSocket connection to ‘ws://localhost:4000/’ failed: Error during WebSocket handshake: Unexpected response code: 400 #4778

I can’t figure out what is the problem?

server:

client:

; if (error) return

The text was updated successfully, but these errors were encountered:

Even I am facing the same issue. Did you find a solution?

Hi @ThiruvenkatamR, Did you try my suggestion, ws://localhost:4000/graphql.

Yes, I tried. But no luck

This is the error

‘The connection to ws://localhost:4000/graphql was interrupted while the page was loading.’

Thanks @vincenterc , this is working in Chrome, but I have this issue in Firefox. Thanks once again.

I continue to get this issue on my Angular 8 app. I seem to have all the correct code

Has anyone had any luck with this?

Hi, I’m facing the same issue. I tried this but it no works! Does anyone have a solution?

Any fix?? Facing the same problem with Apollo Client 3

Nevermind, i forgot to add the /graphql at the end of the url just like @vincenterc pointed out.

I had this: ws://localhost:4000

Working code just in case anyone else faces this:

Adding the /graphql fixed this issue for me too.

Was a reverseproxy configuration issue for me, not a library issue

Adding /subscriptions worked for me

My problem was that I am using an Express server and applying Apollo Server as a middleware. I was not aware that I need to call graphqlServer.installSubscriptionHandlers(expressServer) too, as this was buried deep in the docs. That needs to be called on the HTTP server instance you get returned from expressApp.listen() . Now it is working!

Thank you @danieldunderfelt . You saved my day.

Thank you @danieldunderfelt. You made my year.

This doesn’t sound like an Apollo Client issue, but if anyone thinks it is and can provide a small runnable reproduction using @apollo/client@latest , we’ll take a look. Thanks!

Источник

Устранение ошибок подключения

В этом разделе содержатся сведения об ошибках, которые могут возникнуть при попытке установить подключение к концентратору ASP.NET CoreSignalR.

Код ответа 404

При использовании WebSocket и skipNegotiation = true

При использовании нескольких серверов без липких сеансов подключение может начаться на одном сервере, а затем переключиться на другой сервер. Другому серверу не известно о предыдущем подключении.

Убедитесь, что клиент подключается к правильной конечной точке. Например, сервер размещается на , http://127.0.0.1:5000/hub/myHub а клиент пытается подключиться к http://127.0.0.1:5000/myHub .

Если соединение использует идентификатор и занимает слишком много времени для отправки запроса на сервер после согласования, сервер:

  • Удаляет идентификатор.
  • Возвращает значение 404.

Код ответа 400 или 503

Для следующей ошибки:

Эта ошибка обычно возникает из-за того, что клиент использует только транспорт WebSocket, но протокол WebSocket не включен на сервере.

Код ответа 307

При использовании WebSocket и skipNegotiation = true

Эта ошибка также может произойти во время запроса на согласование.

Наиболее частая причина

  • Приложение настроено для принудительного применения ПРОТОКОЛА HTTPS путем вызова UseHttpsRedirection в Startup или принудительно применяет HTTPS через правило переопределения URL-адресов.
  • Измените URL-адрес на стороне клиента с «http» на «https». .withUrl(«https://xxx/HubName»)

Код ответа 405

Код состояния HTTP 405 — метод не разрешен

Код ответа 0

Код состояния HTTP 0 — обычно проблема CORS , код состояния не предоставляется.

  • Добавьте ожидаемые источники в .WithOrigins(. )
  • Добавьте .AllowCredentials() в политику CORS. Не удается использовать .AllowAnyOrigin() или .WithOrigins(«*») с этим параметром

Код ответа 413

Код состояния HTTP 413 — слишком большой объем полезных данных

Это часто происходит из-за наличия маркера доступа, который превышает 4 КБ.

  • При использовании службы Azure SignalR уменьшите размер маркера, настроив утверждения, отправляемые через службу, с помощью следующих средств:

Временные сбои сети

Временные сбои SignalR сети могут закрыть подключение. Сервер может интерпретировать закрытое подключение как корректное отключение клиента. Чтобы получить дополнительные сведения о причинах отключения клиента в таких случаях , соберите журналы с клиента и сервера.

Источник

WebSocket handshake: Unexpected response code: 400 #468

Description

WebSocket connection to ‘ws://localhost:8443/’ failed: Error during WebSocket handshake: Unexpected response code: 400
error on browser

The text was updated successfully, but these errors were encountered:

Can you provide more info? Your issue does not detail your error. I also need your diagnostic information

I clone the repo and build it locally for the latest updates when I start it on browser console it showing the above error.

This does not tell the whole picture. We need the following:

  • Server Logs
  • your System information (OS and Version [for Linux, specify Kernel and GLIBC version]).

We can’t help you if you don’t have these prerequisites — it helps us to get a better picture and allow to reproduce it.

I also want to point out you might have WebRTC disabled as well — check if you have a WebRTC blocker. If you do, you can’t use code-server.

I’m also seeing this. I’m using MacOS 10.14.

This is what I did:

https://localhost:8443/ just shows a black screen forever, and the JS console repeatedly prints every few seconds:

CC @multishifties if this is known

This is a known Error. Unfortunately I have yet to determine the cause of this.

@nishantbhat May I suggest you change this title to WebSocket handshake: Unexpected response code: 400 so that other users may find it and avoid duplicate issues? (please?)

I had same situation, but I turned on and off a few times and wait a minute. then it was fixed.

but I don’t know why.

I use CentOS 7.x, and used 72152f7 commit

From what I can tell this might be a misconfigured reverse proxy, or the network is actively blocking WebRTC requests.

Issue is marked stale. Closing as no longer relevant to current tree.

Description

WebSocket connection to ‘ws://localhost:8443/’ failed: Error during WebSocket handshake: Unexpected response code: 400
error on browser

Hey, mate, I have faced same issue with Unexpected response code: 200. My app is running behind nginx reversed proxy. I have changed setting to this, and it works for me. I think proxy_pass needs to set to localhost. Hope this will help you out. Happy coding

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

Sorry newbie here, do I just add this to my nginx.config or do I paste it inside/merge it with one of the existing sections (e.g. events < .. >, http < .. >)?

And for completeness server blocks go inside the http block.

Description

WebSocket connection to ‘ws://localhost:8443/’ failed: Error during WebSocket handshake: Unexpected response code: 400
error on browser

Hey, mate, I have faced same issue with Unexpected response code: 200. My app is running behind nginx reversed proxy. I have changed setting to this, and it works for me. I think proxy_pass needs to set to localhost. Hope this will help you out. Happy coding

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

Thank you @soymikey! This works for me.

This issue should be opened because it has not been resolved.

This issue should be opened because it has not been resolved.

Please try to use our setup guide with caddy instead. No evidence of a bug with code-server in this issue.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

WebSocket connection to ‘wss://api-such.andsuch.xyz/graphql/’ failed: Error during WebSocket handshake: Unexpected response code: 400

Hello everyone! I recently deployed a project I’m working on to production. I use DjangoChannelsGraphqlWs for GraphQL subscription functionalities. and I have GraphQL Playground set up via django-graphql-playground. Everything works fine locally — there are no issues whatsoever — subscriptions work fine. However, when I deployed I get the error below when I hit the Play button in Playground:

…and in my browser console, it says

One thing to note is that the application is dockerized. Could it be from there? I don’t think so because it works locally. Here’s what my docker-compose file looks like:

What could be wrong? I’m outta ideas. Thanks!

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

After going through lots of articles, I discovered this one, and this section made me realize the only thing that was wrong was the fact that I didn’t expose port 8000 internally to other docker services. In my docker-compose file, the web service was supposed to have…

… in it. I added that and it was solved. Thanks for all the assistance @audebertc @niloteixeira

Change the settings.py DEBUG to True, then Django should give you more information regarding the bad request. In my case it was an incorrect ALLOWED_HOSTS in settings.py that debug mode showed info enough to fix it.

you must proxying websocket to pass docker…

Popular Topics

Questions

Sign up for Infrastructure as a Newsletter.

Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.

You get paid; we donate to tech nonprofits.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow – whether you’re running one virtual machine or ten thousand.

Источник

Проблема чего: «Ожидание доступного сокета»?

Добрый день!
Замечено следующее поведение и непонятно как его обойти. При множестве вкладок (в основном 8-10+) + новое обращение на сервере приводит к зависанию в вебкитовских браузерах.
Сначала замечено было на сайте КорПортала, но потом заметил забавную вещь — и если открыть форума битрикса чтук 10-15 вкладок, при открытии новой может выскочить такой же прикол.

Как решить данную проблему?
И вообще на уровне чего эта проблема существует? На уровне браузера ограничение, или на уровне сервера (его настроек) или на уровне самого движка битрикса?

Очень грустная ситуация, потому что части сотрудников компании приходится постоянно держать открытыми 10-20+ вкладок — много задач и по ним делать мониторинг, приходится много переключаться.
Уже месяц как перешли на коробку BX24 с мегаплана и мучаемся =(

P.S. Модуль nginx push stream настроен корректно, проверка функций BX24 на него не ругается (вообще все пункты зеленые), отключение в настройках данного модуля «вебСоккетов» (снятие галки) результата не дает.

Цитата
Максим Кучук написал:
Александр Букуров , это ограничение на уровне сервера срабатывает
Цитата
Роман Клевцов написал:
Подскажите, в каком разделе админки можно включить галку «Включить поддержку WebSocket». Тоже намучались (

Добрый день! У нас на свежей установке битрикса тоже есть проблема с websocket.
Конфигурация:
Виртуальная машина BitrixVM7.1.0 с объемом диска 20 Гб для OVA (Sphere and etc.)
1С-Битрикс: Корпоративный портал 17.0.5.
Доступ с внешки настроен через обратный прокси на базе nginx (думаю это ключевой момент)

Описание проблемы:
Постоянно появляются ошибки при работе следующего содержания:

«WebSocket connection to ‘ws://domain.ru/bitrix/subws/?CHANNEL_ID=9ec059209540e24cb61da2ad3072c960/a5dedb91e15e1b16 ­b84fcb7ea951a578&tag=1&time=Fri,%2018%20Mar%202022%2021:00:00%20GMT’ failed: Error during WebSocket handshake: Unexpected response code: 400»

При этом если в конфигурации модуля push and pull убрать галочку с настройки «Включить поддержку WebSocket», то ошибки нет, но тогда появляются ошибки «Ожидание свободного сокета» и часть открытых вкладок в браузере Chrome начинают сильно виснуть.
Проверка конфигурации ошибок по сокетам не показывает вобще, то есть судь по проверке системы — все ок.
Подскажите, возможно надо корректно настроить работу с сокетами за реверс прокси, как это сделать?

Источник

  • #1

I have a docker app on latest Plesk Onyx running (mattermost) and it works perfectly when opened directly through server IP and Docker mapped port (192.168.0.5:33000) Everything works great.

The problem is when I try to make it work through NGINX proxy. If select a domain and set Docker Proxy Rules for the app, it works until a websocket connection is requred. In this moment I get the following error:

WebSocket connection to ‘wss://chat.spntt.com/api/v3/users/websocket’ failed: Error during WebSocket handshake: Unexpected response code: 400

And this repeats for every request. I tried adding additional nginx rules as below but is still does not work.

ocation /api/v3/ {
proxy_pass http://0.0.0.0:33000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection «upgrade»;
proxy_set_header Host $host;
}

I have disabled proxy mode even in the apache&nginx settings. What else can I do?

  • #2

The question is, how can I get websocket to work through nginx reverse proxy ?

IgorG


  • #3

Why not use the correct IP address here?

  • #4

location /api/v3/ {
proxy_pass http://192.168.0.5:33000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection «upgrade»;
proxy_set_header Host $host;
}

I tried it all, docker ip, mapped ip… it just makes no difference

IgorG


  • #5

But have you tried to check that port is available for connection with telnet, at least?

  • #6

I can telnet to 192.168.0.5:33000 and using

GET / HTTP/1.1
HOST: HOSTNAME

and I get the page in plain text on the console, if I use the page through 192.168.0.5:33000 I get the full functionality, eveything works. I am missing something in nginx setup, to get the websocket part of it working when used through the proxied domain.

  • #7

This is supposed to work as from:
mattermost-nginx/mattermost at master · mstrpupt2/mattermost-nginx · GitHub

map $http_x_forwarded_proto $proxy_x_forwarded_proto {
default $http_x_forwarded_proto;
» $scheme;
}
server {
listen 80;
location / {
gzip off;
client_max_body_size 50M;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection «upgrade»;
proxy_set_header Host $http_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 $proxy_x_forwarded_proto;
proxy_set_header X-Frame-Options SAMEORIGIN;
proxy_pass http://app:APP_PORT;
}
}

How can I apply this in plesk?

  • #8

I removed the docker proxy rules for the domain completely. As I can not add map in the additional nginx directives, I just removed the line:

proxy_set_header X-Forwarded-Proto $proxy_x_forwarded_proto;

So it reads out now as below (just to test):

location / {
gzip off;
client_max_body_size 50M;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection «upgrade»;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_set_header X-Frame-Options SAMEORIGIN;
proxy_pass http://192.168.0.5:33000;
}

Now websockets work great, no errors anymore, I can almost use it now.

What I have now are following errors — which prevent it from working correctly:
GET http://chat.spntt.com/api/v3/teams/6zf7npa91fbz7cm7kbm53yhuge/channels/ 404 (Not Found)

  • #9

OK, if I put only the following everything except for web sockets works.

location ~ ^/.* {
proxy_pass http://192.168.0.5:33000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

If I put only the following websocket works, but there are a lot of other errors:

location / {
gzip off;
client_max_body_size 50M;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection «upgrade»;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_set_header X-Frame-Options SAMEORIGIN;
proxy_pass http://192.168.0.5:33000;
}

Now the obvious question is, that I need to combine the two, and everything will work, as each makes one part to work. Just putting both in the additional nginx directives does not fix it, I still get web socket errors.

  • #10

Ok, I fxed it by using this in additinal nginx directives, after turning on he docker proxy rule:

location ^~ /api/v3/users/websocket {

proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection «upgrade»;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_set_header X-Frame-Options SAMEORIGIN;
proxy_pass http://192.168.0.5:33000;
}

THe problem was ^~ which I had to add at the location line

Понравилась статья? Поделить с друзьями:
  • Websocket 1000 error
  • Webrequest cannot resolve destination host duskwood ошибка
  • Webpay код ошибки w0521
  • Webpage not available the webpage could not be loaded because proxy error
  • Webpage error 404