我在名为server.js和index.html
的文件中有以下代码出于某种原因,当我在网络浏览器中导航到我的服务器时,io.on('connection')部分没有在其回调中调用console.log方法。
检查下面的代码,它说明了一切。 的 server.js
var express = require('express'),
app = express(),
io = require('socket.io')(app.Server),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
apiRouter = require('./app/routes/api.js');
//Clears Node Console.
process.stdout.write('\033c');
console.log('Server starting!');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(apiRouter);
app.use(express.static('public'));
app.use('*', function(req, res, next) {
//All requests return single page angular application.
res.sendFile(__dirname + '/public/index.html');
});
mongoose.connect('localhost', 'triviaattack', function(err) {
if (err) {
console.log('An error occured when connecting to the MongoDB Database');
throw err;
}
});
io.on('connection', function(socket) {
console.log('client connected via socket'); //This is the line that isn't being called
});
app.listen(1337, function() {
console.log('Server started successfully @ ' + Date());
});
的index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-route.min.js"></script>
<script src="./app/app.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script>
var socket = io();
</script>
</head>
<body>
<div ng-controller="HomeCtrl">
{{message}}
</div>
</body>
</html>
答案 0 :(得分:0)
找到答案。
要将server.js更改为以下内容,请注意顶部附近的新http变量。仍然有点好奇为什么只是传入app.Server在我原来的帖子中没有工作......哦,好吧。
var app = require('express')(),
http = require('http').Server(app),
io = require('socket.io')(http),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
apiRouter = require('./app/routes/api.js');
//Clears Node Console.
process.stdout.write('\033c');
console.log('Server starting!');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(apiRouter);
app.use('*', function(req, res, next) {
//All requests return single page angular application.
res.sendFile(__dirname + '/public/index.html');
});
mongoose.connect('localhost', 'triviaattack', function(err) {
if (err) {
console.log('An error occured when connecting to the MongoDB Database');
throw err;
}
});
io.on('connection', function(socket) {
console.log('client connected via socket');
});
http.listen(1337, function() {
console.log('Server started successfully @ ' + Date());
});