在express4

时间:2015-11-21 08:30:43

标签: javascript node.js express websocket

我刚刚开始搞乱websockets并表达,我似乎无法使用我现有的架构。

在我宣布路线

之前,我在另一个问题中看到要做以下事情
//this goes prior to your route registration
app.use(function(req, res, next) {
    req.io = io;
});

但我甚至不确定如何将io传递给我的app js以使用上面的代码片段。

我有我的bin / www:我相信这是在express4中引入的?套接字连接正常

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

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

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * attach socket to express
 */
var io = require('socket.io').listen(server);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);


io.sockets.on('connection', function() {
  console.log('!!!sockets io connected!!!');
})

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

我的app.js.我想在哪里使用第一个代码片段吧?但我不确定如何通过' io'到这个文件

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');

/**
 * Route Imports
 */

var app = express();

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

//THIS IS WHERE I WOULD PUT IT???? assuming I can pass IO into this??
app.use(function(req, res, next) {
    req.io = io;
});

/**
 * Routes
 */
var router = require('./router')(app);

module.exports = app;

路由器index.js

/**
 * The Index of Routes
 */

module.exports = function (app) {

  app.use('/test', require('./routes/test'));
}

最后是路线,我假设一旦我在我的app.js中得到第一个片段,这会有效,因为它会被附加到req?

var express = require('express');
var router  = express.Router();

router.get('/', function (req, res) {
   //I WANT SOCKET TO JUST RESPOND WITH ANYTHING BUT I CANT GET 
   //AN INSTANCE OF IO IN HERE
   req.io.emit('test', 'hihi');
});

router.post('/', function (req, res) {
  test.save(function (err) {

    if (err) {
      console.log(err);
      res.status(500).json({
        'message': 'error'
      });
    } else {
      // Log success
      console.log('Success');
      req.io.emit('test:added', test);
      res.status(201);
    }

  });
});
module.exports = router;

**注意:删除了大量代码以便于阅读**

1 个答案:

答案 0 :(得分:0)

主要模块:

var app = express();
// ...
var server = http.createServer(app);
// ...
var io = require('socket.io').listen(server);

// ...

app.use(function (req, res, next) {
  req.io = io;
})

require('../app')(app); 
require('../routes')(app);    

您的应用模块会公开app个实例,因此您可以在主模块中使用它,但您可以访问io。简单。