Express: upgrade event does not fired

Created on 20 Feb 2015  路  2Comments  路  Source: expressjs/express

It seemes that express@4 and express@3 does not fire upgrade event when client WebSocket requests it. Here's the code. Let's first try to use std http module:

var
    http = require('http');

var server = http
.createServer(function (rq, rs)
{
    rs.end('<title>test page</title>');
})
.listen(8080, console.log.bind(console, 'server started'));

server.on('upgrade', function (_, socket)
{
    console.log('upgrade event fired', socket);
});

On client:

new WebSocket('ws://localhost:8080');

This works. Server logs upgrade event, client does not throw any errors. Now, let's replace http with express. Here's the analogous code with required adaptations:

var
    server = require('express')();

server.get('/', function (rq, rs)
{
    rs.end('<title>test page</title>')
})
.listen(8080, console.log.bind(console, 'server started'));

server.on('upgrade', function (_, socket)
{
    console.log('upgrade event fired', socket);
});

The client is the same. This code does not work: server does not fire event, and client throws handshake error.

I'm trying to integrate express with ws module. It can use express instance and relies on upgrade event. I've logged through its code, and looks like error somewhere on express side. Or maybe I don't understand express API properly. Anyway, I'm looking for help.

question

Most helpful comment

Express is an app, not an http server. Your code should be as follows:

var
    http = require('http');
var
    app = require('express')();

app.get('/', function (rq, rs)
{
    rs.end('<title>test page</title>')
})

var server = http
.createServer(app)
.listen(8080, console.log.bind(console, 'server started'));

server.on('upgrade', function (_, socket)
{
    console.log('upgrade event fired', socket);
});

All 2 comments

Express is an app, not an http server. Your code should be as follows:

var
    http = require('http');
var
    app = require('express')();

app.get('/', function (rq, rs)
{
    rs.end('<title>test page</title>')
})

var server = http
.createServer(app)
.listen(8080, console.log.bind(console, 'server started'));

server.on('upgrade', function (_, socket)
{
    console.log('upgrade event fired', socket);
});

@dougwilson, this helps, thanks for clarification.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zackarychapple picture zackarychapple  路  3Comments

cuni0716 picture cuni0716  路  3Comments

nove1398 picture nove1398  路  3Comments

dmaks9 picture dmaks9  路  3Comments

extensionsapp picture extensionsapp  路  3Comments