0
我在一個名爲server.js和index.html的文件中有以下代碼NodeJS + Socket.io連接事件處理程序未被成功調用?
由於某些原因,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>