我按照教程在MEAN堆栈应用程序中尝试socket.io,但我不知道如何继续。我在其中一个node.js路由中有以下代码。计划是连接套接字,但为此我需要服务器变量。有谁知道如何将其导入我的路线文件?
Node.js中的电影聊天路径文件
var express = require('express');
var router = express.Router();
var socket = require('socket.io');
var io = socket(server);
io.on('connection', function(socket){
console.log('made socket connection')
})
module.exports = router;
App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var movieChatRoutes = require('./routes/movieChat');
var app = express();
mongoose.connect('mongodb://localhost:27017/moviemeter');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
next();
});
app.use('/movieChat', movieChatRoutes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
res.render('index');
});
module.exports = app;
这是他们在教程中获得它的方式(通过使用app.listen())