Monday, April 9, 2018

WebSocket connection to 'wss://' Error during WebSocket handshake: Unexpected response code: 400

Leave a Comment

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.

Just in case, all the code for the app is available on https://github.com/noduslabs/infranodus

1 Answers

Answers 1

Use a secure URL for your initial connection, i.e. instead of "http://" use "https://". If the WebSocket transport is chosen, then Socket.IO should automatically use "wss://" (SSL) for the WebSocket connection too.

If you are not specifying any URL when you call io(), since it defaults trying to connect to the host that serves the page, either you have to provide url or change to https

  var socket = io.connect('https://localhost', {secure: true}); //remote url 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment