I
I
IDONTSUDO2019-12-06 11:34:39
Node.js
IDONTSUDO, 2019-12-06 11:34:39

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
5dea1128ac203888856690.png
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}`))

test.router.js
const express = require("express")
const { test } = require("../controllers/test")

const router = express.Router({mergeParams: true});

router.get('/',test)

module.exports = router

test.controller.js
exports.test = async (req,res) =>{
    console.log(200)
}

How can I make the io connection available at the level of the entire application?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2019-12-06
@hzzzzl

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 question

Ask a Question

731 491 924 answers to any question