问题
snippet below is clear
// 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)
but here
app.use('/students', studentRoute)
I want to pass io
to studentRouter
, How can I do that ?
and this is my studentRouter :
// student route
const express = require('express');
const router = express.Router();
router.route('/').get((req, res, next) => {
res.send("hi")
})
module.exports = router;
回答1:
You can change studentRouter
to export a function that you can call and pass io
to it:
const studentRouter = require('./routes/student')(io);
Then, inside the studentRouter
file, instead of exporting the router directly, you export a function:
module.exports = function(io) {
// define your router and set it up
// you can then use io in your routes here
return router;
}
When you export a single function like this from a module, it is often called a "module constructor" and it allows you to pass arguments that the module can then use when setting itself up. You just put the module's contents inside the function and it can then use the arguments in all of its code.
来源:https://stackoverflow.com/questions/61578047/pass-socket-io-to-router-module-in-node-js