【发布时间】:2019-05-30 19:33:32
【问题描述】:
我在 Express 中使用 app.post 方法,如下所示:
app.post('/race', function(req,res) {
let raceResponse = {
user_name: req.body.userName
}
console.log('Express has received race.');
//Socket.IO
let race = io.of('/race').on('connection', (socket) => {
console.log('A user has entered the race!');
socket.on('racePageReady', function() {
console.log('race page ready recieved');
socket.emit('racePageInfo', raceResponse);
});
socket.on('createRoom', function(roomName) {
socket.join(roomName);
let clients = io.sockets.adapter.rooms[roomName].sockets;
console.log("A room with the name " + roomName + "was created.");
console.log(clients);
socket.emit('roomCreated', clients);
});
socket.on('joinRoom', function(roomName) {
socket.join(roomName);
let clients = io.sockets.adapter.rooms[roomName].sockets;
console.log('A user joined the room with the name: ' + roomName + ". The user's name is " + raceResponse.user_name);
console.log(clients);
socket.emit('roomCreated', clients);
});
});
res.sendFile(path.join(__dirname, '/client/race/index.html'));
}
页面发送正常,但console.log 和所有其他 Socket.IO 内容都没有发生。我发现这很奇怪,因为我有一个 不同 app.post 方法可以正常工作,所有 console.logging 和 Socket.IO 业务都会发生。代码如下:
app.post('/city', function(req,res) {
let cityResponse = {
user_name: req.body.userName
}
console.log('Express has received city.');
//Socket.IO
let city = io.of('/city').on('connection', (socket) => {
socket.id = Math.random();
socket.name = cityResponse.user_name;
SOCKET_LIST[socket.id] = socket; //defined earlier
User.onConnect(socket); //defined earlier
socket.on('cityPageReady', function() {
socket.emit('cityPageInfo', cityResponse);
console.log('city page ready recieved');
});
console.log('A user has connected to the city!');
console.log("Socket: " + socket);
console.log("Socket ID: " + socket.id);
console.log("SOCKET_LIST: ");
console.log(SOCKET_LIST);
socket.on('chat message', function(msg, user) {
console.log('User ' + user + ' sent the message : ' + msg);
socket.emit('chat message', msg, user);
});
});
res.sendFile(path.join(__dirname, '/client/city/index.html'));
});
据我所知,这两种方法看起来几乎相同,除了中间的 Socket.IO 东西。我相当肯定io.of 方法是正确的,因为它适用于城市页面,但不适用于比赛。
唯一的另一个区别是访问两个页面的方式。 City 页面通过带有action 属性的 HTML 表单访问,而 Race 页面通过带有 href 属性的 HTML 链接(在 City 页面上)访问。
两种方法如下所示:
城市
<form id="cityForm" action="http://localhost:4000/city" method="POST">
User name: <input type="text" name="userName">
button type="submit" id="formSubmit">Submit</button>
</form>
种族
<div><a href="http://localhost:4000/race"></div>
谁能明白为什么会发生这种奇怪的行为?如果需要任何其他信息,请告诉我,以便我将其包含在内。
【问题讨论】:
-
您的
race代码是否应该指向city?顺便说一句,这将发送一个get。 -
您的 cmets 与代码 sn-ps 不匹配:RACE 显示城市的 URL。假设您在那个 URL 中实际上是指
/race,那么请求中没有传递 name 属性。 -
那是一个错字。 div 实际上指向
http://localhost:4000/race。
标签: javascript html node.js express socket.io