Answer the question
In order to leave comments, you need to log in
Express + Socket.io pass IO to router?
As far as I know Express is built around middleware. But for some reason I can't access io in my handler.
The structure of my
main.js application
const express = require('express')
const http = require('http')
const socketIO = require('socket.io')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const port = 4001
const app = express()
const server = http.createServer(app)
const io = socketIO(server)
const Routes = require('./router/test.js')
// console.log(io) здесь я могу получить доступ к io переменной
app.use(function(req,res,next){
// console.log(io) а в промежуточном обработчике не могу
req.io = io;
next();
});
app.use(morgan("dev"))
app.use(bodyParser.json())
app.use("/", Routes)
server.listen(port, () => console.log(`Listening on port ${port}`))
const express = require("express")
const { test } = require("../controllers/test")
const router = express.Router({mergeParams: true});
router.get('/',test)
module.exports = router
exports.test = async (req,res) =>{
console.log(200)
}
Answer the question
In order to leave comments, you need to log in
should work, but how do you know that
?
in test.controller.js also req.io === undefined?
just wrote this yesterday
const express = require('express')
const app = express()
const server = require('http').createServer(app)
const io = require('socket.io')(server)
app.use('/', function(request, response, next) {
request.io = io
next()
})
............
router.post('/', async (req, res) => {
const { socketId } = req.body
req.io.to(socketId).emit('fetchstart') // всё ок
.....
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question