2017-11-02 12 views
0

IBM Bluemix에서 Node.js, Express 및 Socket.io로 앱을 만들려고합니다. EJS를 사용하고 있습니다. 뷰 엔진. 이것은 관련 내 코드의 일부이다 - 나는 로컬 호스트로 이동하는 경우 이제EJS에서 Socket.io를 사용하면 "보낸 후 헤더를 설정할 수 없습니다"라는 오류가 발생합니다.

const express = require('express'); 
const app = express(); 
//copied from socket.io tutorial 
const http = require('http').Server(app); 
const io = require('socket.io')(http); 
app.set('view engine', 'ejs'); 
app.set('views', path.join(__dirname, '../templates')); 
... 
app.get('/', function (req, res) { 
    logger.info('index'); 
    return res.render('index'); 
}); 
... 
const port = process.env.PORT || localConfig.port; 
http.listen(port); 

: 3000, 내가 로그에서 오류

Error: Can't set headers after they are sent. 
at validateHeader (_http_outgoing.js:489:11) 
at ServerResponse.setHeader (_http_outgoing.js:496:3) 
at ServerResponse.header (/home/aniket/Documents/HumbleHelper/node_modules/express/lib/response.js:767:10) 
at ServerResponse.contentType (/home/aniket/Documents/HumbleHelper/node_modules/express/lib/response.js:595:15) 
at ServerResponse.send (/home/aniket/Documents/HumbleHelper/node_modules/express/lib/response.js:145:14) 
at done (/home/aniket/Documents/HumbleHelper/node_modules/express/lib/response.js:1004:10) 
at tryHandleCache (/home/aniket/Documents/HumbleHelper/node_modules/ejs/lib/ejs.js:228:10) 
at View.exports.renderFile [as engine] (/home/aniket/Documents/HumbleHelper/node_modules/ejs/lib/ejs.js:437:10) 
at View.render (/home/aniket/Documents/HumbleHelper/node_modules/express/lib/view.js:135:8) 
at tryRender (/home/aniket/Documents/HumbleHelper/node_modules/express/lib/application.js:640:10) 

을 얻을, 나는 '인덱스'가 호출 된 것을 알 수 있습니다 두 번 누른 다음 오류가 발생합니다. 그러나이 줄을 제거하면 -

const io = require('socket.io')(http); 

잘 작동합니다. res. *** 함수를 두 번 이상 호출하면이 문제가 발생할 수 있다는 다른 질문을 읽었습니다. 내 생각 엔 서버를 통해 socket.io를 구성하면 무언가가 발생합니다.

버전 :

socket.io : 2.0.4

표현 : 4.6.2

EJS 2.5.7

노드 : 6.9.0

편집

댓글 달기/모든 모듈의 주석을, 나는

require('appmetrics-dash').attach(); 
require('appmetrics-prometheus').attach(); 
+0

'반환 res.render ('인덱스');'필요하지 반환 반환을 제거 –

+0

@RIYAJKHAN는 –

답변

0

대부분의 경우, 당신은 입술을 처리 할 수있는 socket.io 리스너를 구성하고 내 응용 프로그램의 상단에, 원인 여기 발견했습니다. 따라서 Socket.io가 다른 브로드 캐스트를 받으면 이미 보낸 이전 res를 사용합니다.

이 문제를 해결하려면 청취자를 제거한 후 새 res로 새 수신기를 구성 할 수 있도록 수신기를 제거하십시오. 예 :

socket.on('example', function(data){ 
    socket.removeAllListeners('example'); 
    res.send(data); 
}); 

EDIT : 웁스! 어쨌든 나는 틀린 LOL 질문을 읽었다. 이 시도 :

var express = require('express'); 
var app = express(); 
var http = require('http').createServer(app); 
var io = require('socket.io').listen(http); 
+0

그런 시도 같은 오류를 발생합니다. 작동하지 않았어. 내 생각 엔 socket.io에 똑같은 포트에서 고속 수신 대기로 인해 오류가 발생했다는 것 –