0
我目前正在爲特定網站添加實時聊天。我使用Express JS軟件包,並且初始化信息(即啓動/監聽服務器等)位於'www/bin'中(默認情況下)。can not app.get('foo')(Express/Node JS)
所以,這是我的初始化文件(即「WWW/bin中」):
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('nodeblog:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen to Sockets
*/
var io = require('socket.io').listen(server);
app.set('socketio', io); // FIXME: Cannot app.get('socketio') w/out req
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
而且事情是,我不能「得到」這SocketIO聲明,因爲我需要在路由器的一個文件來在客戶端/服務器之間交換消息
下面是這條路線文件:
var express = require('express');
var router = express.Router();
var app = express();
// Models
var auth = require('../models/auth');
var io = app.get('socketio');
router.get('/', auth.ensureAuthenticated, function(req, res, next) {
res.render('chat', {
title: 'Chat'
});
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('chat message', function(msg) {
io.emit('chat message', msg);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
module.exports = router;
所以,當我嘗試app.get(「socketio)」返回undefined
你知道我怎麼需要正確地申報這個app.get('socketio',io)
這樣我可以在任何地方訪問它(但不是到請求的方法)
錯誤:
chat.js:15
io.on('connection', function(socket){
^
TypeError: Cannot read property 'on' of undefined