下面的代码段很清楚
// app.js
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const studentRouter = require('./routes/student')
app.use('/students', studentRouter)
但是在这里
app.use('/students', studentRoute)
我想将io
传递给studentRouter
,该怎么做?
这是我的studentRouter:
// student route
const express = require('express');
const router = express.Router();
router.route('/').get((req, res, next) => {
res.send("hi")
})
module.exports = router;
答案 0 :(得分:0)
您可以更改studentRouter
以导出可以调用的函数并将io
传递给该函数:
const studentRouter = require('./routes/student')(io);
然后,在studentRouter
文件内部,而不是直接导出路由器,而是导出函数:
module.exports = function(io) {
// define your router and set it up
// you can then use io in your routes here
return router;
}
当从模块中导出像这样的单个函数时,通常将其称为“模块构造函数”,它允许您传递参数,然后模块在设置自身时可以使用这些参数。您只需将模块的内容放入函数中,然后就可以在其所有代码中使用参数。