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.