Node Express 3x socket IO testing
I try to add socket IO to my project but I didn't manage to make it work.
my app.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
//IO Config
var io = require("socket.io").listen(server);
io.sockets.on('connection', function (socket) {
socket.emit('makealert');
});
my views:
extends layout
script(type='text/javascript' src='../node_modules/socket.io/lib/socket.io.js')
script(type='text/javascript'
var socket = io.connect();
socket.on('makealert', function () {
alert('Boom');
});
)
block content
h1= title
p Welcome to #{title}
my route:
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
I have 2 problems: -first what's the way to find socket.io.js (in a jade view) -second, is my app.js OK ? -thrid, my console said:
SyntaxError: Node/thrid_app/demo-express/views/index.jade:5 3| script(type='text/javascript' src='../node_modules/socket.io/lib/socket.io.js') 4|
5| script(type='text/javascript' 6| var socket = io.connect(); 7| socket.on('makealert', function () {
Ty for yours helps
The error you have mentioned is due to syntax error in jade
change this line
script(type='text/javascript'
var socket = io.connect();
socket.on('makealert', function () {
alert('Boom');
});
)
to
script(type='text/javascript')
var socket = io.connect();
socket.on('makealert', function () {
alert('Boom');
});
Some mistakes in your code, also you seem to be using old jade syntax.
script(type='text/javascript' src='../')
. It should be script(type='text/javascript', src='../')
script
must be used as script.
or script(...).
. Likewise for style
. Your last script tag in view is closed incorrectly
script(type='text/javascript'
...
)
Should be like this
script(type='text/javascript')
...
上一篇: 从0.9 socket.io迁移