Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'headers already sent' error while using restify with socket.io

I'm following official restify guide to use socketio with restify.

api.js

var mongoose = require('mongoose');
var restify = require('restify');
var fs = require('fs');
var server = restify.createServer({
  name: 'myapp',
  version: '1.0.0'
});
var io = require('socket.io')(server);
server.get('/', function indexHTML(req, res, next) {
    fs.readFile(__dirname + '/sockettest.html', function (err, data) {
        if (err) {
            next(err);
            return;
        }

        res.setHeader('Content-Type', 'text/html');
        res.writeHead(200);
        res.end(data);
        next();
    });
});
io.on('connection', function(socket){
  console.log('a user connected');
});

sockettest.html

<html>
<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>
<script>
  var socket = io();
</script>
</html>

When I browse to localhost:3000 I'm getting this error:

myapp listening at http://[::]:3000
_http_outgoing.js:350
    throw new Error('Can\'t set headers after they are sent.');
    ^

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:350:11)
    at ServerResponse.format (/host/bid-it/bid-it/node_modules/restify/lib/response.js:145:10)
    at ServerResponse.send (/host/bid-it/bid-it/node_modules/restify/lib/response.js:338:14)
    at emitRouteError (/host/bid-it/bid-it/node_modules/restify/lib/server.js:201:13)
    at onRoute (/host/bid-it/bid-it/node_modules/restify/lib/server.js:754:21)
    at Router.find (/host/bid-it/bid-it/node_modules/restify/lib/router.js:608:5)
    at Server._route (/host/bid-it/bid-it/node_modules/restify/lib/server.js:747:21)
    at routeAndRun (/host/bid-it/bid-it/node_modules/restify/lib/server.js:705:14)
    at Server._handle (/host/bid-it/bid-it/node_modules/restify/lib/server.js:725:9)
    at Server.onRequest (/host/bid-it/bid-it/node_modules/restify/lib/server.js:326:14)
    at emitTwo (events.js:87:13)
    at Server.emit (events.js:172:7)
    at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:525:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:88:23)

Can you please tell me what is I'm missing?

like image 383
Eray Avatar asked Nov 19 '15 23:11

Eray


1 Answers

Using

var io = require('socket.io')(server.server);

instead of

var io = require('socket.io')(server);

solved my problem.

like image 148
Eray Avatar answered Oct 21 '22 20:10

Eray