'标题已发送'使用socket.io进行restify时出错

时间:2015-11-19 23:07:27

标签: node.js sockets socket.io restify

我跟随official restify guide使用socketio来解决问题。

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>

当我浏览localhost:3000时,我收到此错误:

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)

你能告诉我我错过了什么吗?

2 个答案:

答案 0 :(得分:12)

使用

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

而不是

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

解决了我的问题。

答案 1 :(得分:1)

尝试在创建restify服务器的位置内将socket.io参数设置为true,如下所示:

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

这解决了我的问题。