Question

I want to use Primus with Express. Primus as abstraction layer to websockets. I used the Primus examples works fine - I used a basic Express examples - works fine. But somehow I can get them working together.

index.html (just the standard primus example html) & primus.js are in folder ./public

Here is what I'm doing.

var express = require('express');
var Primus = require('primus');
var http = require('http');
var path = require('path');
var app = express();

var server = require('http').createServer(app)
, primus = new Primus(server, { transformer: 'engine.io' });


app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(express.json());       // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies
app.use(express.methodOverride());

app.use(app.router);
app.use(express.static(__dirname + '/public'));


// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

primus.on('connection', function connection(spark) {
    console.log('new connection');
    spark.write({ Welcome: 'Hello!' });
});

primus.save(__dirname +'/public/primus.js');

/* the normal express start
http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
});
*/

server.listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
});

Output when accessing

http://localhost:3000/index.html


Express server listening on port 3000
GET /index.html 200 73ms - 5.22kb

index.html served correctly. but no request for primus.js shows up. And index.html shows 400 error on get primus.js

When I disable the primus part in the code above and use the normal express start I get the following output:

Express server listening on port 3000
GET /index.html 200 79ms - 5.22kb
GET /primus.js 200 69ms - 96.54kb

So all served correctly. Prmius works on client but of course nobody at server side answering as I had primus disabled.

Any idea what's wrong?

Was it helpful?

Solution

I think the problem appears because Primus intercepts all requests starting with /primus, so Express cannot serve primus.js file.

I also suppose that in your HTML file you have something like:

<script src="/primus.js"></script>

Try to replace it with:

<script src="/public/primus.js"></script>

And then replace this line:

app.use(express.static(__dirname + '/public'));

with this one:

app.use('/public', express.static(__dirname + '/public'));

Update

Since we changed static files URI, we have to serve index.html manually:

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/public/index.html');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top