gpt4 book ai didi

javascript - socket.on 在 io.sockets.on('connection,..) 之外不起作用

转载 作者:行者123 更新时间:2023-12-02 23:20:39 24 4
gpt4 key购买 nike

我尝试以这种方式从路由页面捕获消息:

路由页面


router.get('/', function(req, res, next){
var socket= req.app.get('socketio');
socket.on('Ok', () => console.log("OK"));
res.render('exercises', {title: 'Exercises', ex: values[0]});
})

APP.JS

io.sockets.on('connection', function(socket){
console.log('Connesso');
app.set('socketio', socket);
})

为了在路由页面中捕获来自客户端的“Ok”事件,但它不起作用,我不明白为什么,因为我已经使用 app.set 传递了套接字

编辑我在这里发出事件:

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080/');
</script>
<div id="addex" hidden>
<form name="newex" method="get">
<h1>Inserisci esercizio</h1>
<p>Nome</p>
<input id="name" name="name" type="text"></input>
<p>Descrizione</p>
<input id="description" name="description" type="text"></input>
<input type="submit"></input>
</form>
</div>
<button id="add" type="button" onclick=""> Add </button>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
<ul>
<p>Excercises:</p>
<% ex.forEach(value => { %>
<li><%= value.name %></li>
<% }); %>

</ul>
<script type="text/javascript">
add.onclick = function(event){
addex.hidden = false;
}
newex.onsubmit = function(event){
event.preventDefault();
socket.emit('message', {name: document.getElementById('name').value, desc: document.getElementById('description').value});

}
</script>
</body>
</html>

最佳答案

尝试遵循以下示例:

const socketServer = SocketService.io = socketIo(server, {
path: process.env.WEBSOCKETS_PATH || "/socket.io",
handlePreflightRequest: (req, res) => {
const headers = {
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Origin": req.headers.origin ? req.headers.origin : "*", // or the specific origin you want to give access to,
"Access-Control-Allow-Credentials": true,
};
res.writeHead(200, headers);
res.end();
},
});

export let socketConnection;

socketServer.on("connect", async (connection) => {
logger.log("Successfully established socket connection.");
connection.emit("connection", { code: 200, message: "Socket connection established." });
socketConnection = connection;
connection.on("my event", async (streamConnection) => {
logger.log("Successfully established socket my event.");
connection.emit("connection", { code: 200, message: "My event established, listening on 'my event' event." });
});
});

现在,在代码的其他部分,您可以导入“socketConnection”并使用它。

关于javascript - socket.on 在 io.sockets.on('connection,..) 之外不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com