Error "headers have already been sent" when using restify using socket.io

I am following the official patch guide for using socketio with reify.

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 go to localhost:3000 , I get 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) 

Could you tell me what I am missing?

+5
source share
2 answers

Using

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

instead

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

solved my problem.

+12
source

Try setting socket.io to true inside the place where you are creating your recovery server, for example:

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

This solved the problem for me.

0
source

Source: https://habr.com/ru/post/1236379/


All Articles