Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

227
Visualizações
How to combine socket.io and node.js with middleware?

I am now trying to combine socket.io and node.js in one project. Node.js alone is working well. My codes are like below.

authMiddleware.js

if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    try {
      token = req.headers.authorization.split(" ")[1];
      const decoded = jwt.verify(token, process.env.JWT_SECRET);

      req.user = await User.findById(decoded.id).select("-password");
      next();
    } catch (err) {
      res.status(401);
      throw new Error("Not authorized, token failed");
    }
  }

  if (!token) {
    res.status(404);
    throw new Error("Not authorized, no token");
  }
});

server.js

app.use("/api/users", userRoutes);
app.use("/api/homes", homesRoutes);

const io = require('socket.io')(http, {
    cors: {
        origin: '*',
        methods: ['GET', 'POST']
    }
});
io.on('connection', (socket) => {
    console.log('-----------Hello socket world---------------');
    socket.on("GET_USERS", GetUsers(io, socket))
    socket.on("GET_CURRENT_USER", GetCurrentUser(io, socket))
})
app.listen(
    PORT,
    console.log(
      `Server running in ${process.env.NODE_ENV} mode on port ${PORT}`
    )
  );

The problem is when socket.emit happens, it go through authMiddleware.js and send error since I don't set header for socket.io, in my thought. I setted header but not working.

App.js

async function getUserData() {
            const token = localStorage.getItem("userToken");
            const socket = io(localhost:5000,
                {headers: {//I trying to add header here, but not working.
                  Authorization: "Bearer " + token,
            }});
            if (token && !state.user.auth) {
                try {
                    socket.emit("GET_CURRENT_USER", token);
                    socket.on("getCurrentUser_error", (msg) => {
                        alert(msg);
                    })
                    socket.on("getCurrentUser_success", (data) => {
                        dispatch({
                            type: USER_LOGIN_SUCCESS,
                            payload: { ...data, auth: true },
                        });
                    })
                } catch (err) {
                    dispatch({
                        type: USER_LOGIN_FAIL,
                        error: err,
                    });
                }
            }
        }

I have headache for this for 3 days now and don't know how to deal with it.

It will be great help, if someone kindly help me.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda