我正在尝试将Express和Socket连接连接在一起。我想我的设置很整洁,但不是在我想这样做的时候:
app.post()
然后将输入发送到导出,该导出处理所有数据库连接。这可以单独用套接字完成吗?是。但我不是那种生活。
RoomRouter.js
exports.createRoom = (req, response) => {
new Room(req.body).save((err, room) => {
response.status(200).send(room);
});
};
app.js
/*
* Express setup is left out, because we don't need to focus on that.
* "app" is const app = express();
*/
const RoomRouter = require("./RoomRouter");
app.post("/room/create", RoomRouter.createRoom);
io.on("connection", (socket) => {
//I want to broadcast the room to everyone
//io.emit("newRoom", room);
});
Express部分工作正常,POST工作正常。现在,我如何将Socket.IO连接到那个,所以我可以向所有人广播已添加新房间?
答案 0 :(得分:1)
我不确定你真正想要的是什么,但是如果你想在你的路线中使用套接字io,我认为你必须声明这样的路线:
<强> RoomRouter.js 强>
exports.createRoom = (io) => {
return (req, response) => {
new Room(req.body).save((err, room) => {
io.emit("newRoom", room);
response.status(200).send(room);
});
};
};
在 app.js
中app.post("/room/create", RoomRouter.createRoom(io));
希望它有所帮助。