socket.io.js上的NodeJS Express 4.9和Socket.IO - 404错误

时间:2014-09-25 12:10:58

标签: node.js express socket.io

我正在尝试使用Socket.IO创建一个Express应用程序。似乎Express已经发生了很大的变化,大多数关于让2人一起工作的代码已经过时了。这就是我所拥有的:

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 routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

var http = require('http').Server(app);
var io = require('socket.io').listen(http);
io.on('connection', function(socket){
    console.log('a user connected');
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__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('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;

服务器启动正常并说

info - socket.io started

然而,前端在http://example.com:3000/socket.io/socket.io.js

上有404错误

修改

如果我添加

http.listen(8080);

服务器在端口3000和8080上运行两次,3000版本不加载socket.io.js而8080版本加载。我怎么能拥有它,所以服务器只运行在3000?将其更改为3000错误,并尝试听两次

2 个答案:

答案 0 :(得分:2)

答案是在bin / www.js而不是app.js中进行更改

#!/usr/bin/env node
var debug = require('debug')('test1');
var app = require('../app');

app.set('port', process.env.PORT || 3000);

var http = require('http').Server(app);
var io = require('socket.io')(http);

var server = http.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});

答案 1 :(得分:1)

io包含更改为:

var io = require('socket.io')(http);

向底部添加类似:

http.listen(3000, function() {
  console.log('Listening on port %d', http.address().port);
});