我正在尋找如何在 nodejs 控制器功能中使用套接字發射、廣播功能的答案?. 我正在初始化我的io.on("connection")內部index.js
檔案。
我正在添加我的檔案結構,任何人都可以幫助我如何傳遞我的套接字或如何在我的控制器中使用我的套接字實體。

假設我有這條快速路線:
router.post("/current-uzone-user/update-bio", verifyToken, updateUserBio);
在我的功能中:
export const updateUserBio = async (req, res) => {
try {
const { bio } = req.body;
if (!bio) return res.status(400).send("Bio is required");
const user = await UUser.findById(req.user._id).exec();
if (!user) return res.status(400).send("User not found");
if (user._id != req.user._id)
return res.status(400).send("You are not authorized to delete this todo");
user.bio = bio;
await user.save();
return res.status(200).send("User bio updated successfully");
} catch (err) {
//console.log(err);
await sendSlackMessage({
text: `Server error at ${new Date(
Date.now()
).toLocaleString()} => ${JSON.stringify(err, null, 4)}`,
});
return res.status(400).send("Something went wrong");
}
};
假設我想在更新生物成功或失敗后發出一個套接字訊息。
有人可以幫我在這里怎么做。謝謝??
uj5u.com熱心網友回復:
您可以使用以下代碼從任何地方訪問套接字并發出事件。
//app.js or index.js
const app = express();
var http = require("http");
var server=http.createServer(app).listen(2525, (req, res) => {
console.log("Server running on", 2525);
});
var socketIO = require("socket.io");
var io = socketIO(server);
global.io = io //Importent line
//Add the below statement to your controller code
global.io.emit("eventname", "yourdata"); //Importent line
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/524257.html
上一篇:如何通過套接字發送自定義Python物件而不參考套接字另一側的物件類?
下一篇:Mojolicious奇怪的餅干
