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

2

6

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?

Knifeedged answered 19/11, 2015 at 23:7 Comment(0)
K
13

Using

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

instead of

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

solved my problem.

Knifeedged answered 20/11, 2015 at 0:21 Comment(0)
U
2

Try setting the socket.io parameter to true inside of where you create your restify server, like so:

var server = restify.createServer({
     name: 'myapp',
     version: '1.0.0,
     socketio: true
});

This solved the problem for me.

Ultrafilter answered 21/7, 2017 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.