伙计们,我有一个基本的套接字连接,我想在测试请求后向客户端发送消息。我尝试了正常的导出和eventemitter,但无法管理它
//this is server.js file
const express = require("express");
const testRoutes = require("./routes/testRoutes");
const app = express();
//Socket.io connection
const server = require("http").createServer(app);
const io = require("socket.io")(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
//Socket.io communication
io.on("connection", (socket) => {
console.log("socket on");
socket.on("newMessageToServer", ({ message, username }) => {
console.log("messagefromclient", message, username);
io.emit("newMessageToClient", { message, username }); //<-- i want to reach this line from another file
});
});
//Routes
app.use("/test", testRoutes);
//Server
const port = process.env.port || 5000;
server.listen(port, () => {
console.log("listening " + port);
});
字符串
所以我想在点击下面的/test/test端点后向客户端发送一条消息
//this is testRoutes.js file
const express = require("express");
const router = express.Router();
router.post("/test", async (req, res) => {
console.log("testsocket");
// -- I want to use socket here like this
//io.emit("newMessageToClient", { message, username });
});
module.exports = router;
型
1条答案
按热度按时间e5njpo681#
让你的
testRoutes
导出一个接受io
接口并返回路由器的函数。例如字符串
然后在
server.js
文件中使用它型