在nodejs路由中导入模块

时间:2018-05-29 22:33:46

标签: javascript node.js express socket.io node-modules

我在index.js文件中声明了socket.io,并且我将soket对象传递给路由模块。

junit 3.8.1

routes.js

const express = require('express');
const app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var MongoClient = require('mongodb').MongoClient;
var server = require('http').Server(app);
var io = require('socket.io')(server);
var routes = require('./routes/routes')(io);

const dbb = mongoose.connect("mongodb://xxx:xxx@ds137600.mlab.com:37600/tasksdb");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));

app.use('/', routes);
var server= app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
})

如何将它转移到routes.js?有什么不同的方法呢?我仍然不太清楚模块是如何工作的

1 个答案:

答案 0 :(得分:0)

对于服务器:

const app = express();

app.use(logger('tiny'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use((req, res, next) => {
  const origin = req.headers.origin;
  if (allowed_header.indexOf(origin) > -1) {
    res.header('Access-Control-Allow-Origin', origin);
  }
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, gutsyJwt, Accept'
  );
  next();
});

app.io = require('socket.io')({
  origins: ['*:*'],
});

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

module.exports = app;

然后在路线:

module.exports = app => {
  app.post('/api/bar', (req, res) =>
   fooController.bar(req, res, app.io)
  );
};

然后在控制器中:

module.exports = {
  bar(req, res, io) {
    io.emit('message', req.body.message);
    res.status(200).send({msg: 'Message broadcasted!'});
  },
};

在这篇文章中,如果您需要更多参考,它也会问类似的问题。 ExpressJS how do I pass objects with state (eg. connections)?