我在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
方法是正确的,因为它适用于“城市”页面,但不适用于种族。
唯一的区别是访问两个页面的方式。通过具有action
属性的HTML表单访问“城市”页面,而通过具有href
属性的HTML链接(在“城市”页面上)访问“竞赛”页面。
这两种方法如下所示:
城市
<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>
谁能看到为什么发生这种特殊行为?如果需要其他信息,请告诉我,以便包括在内。
答案 0 :(得分:2)
单击HTML链接时,浏览器将执行GET HTML请求。当您提交表单(使用method =“ POST”)时,浏览器会发出POST请求。
使用app.post()
时,您告诉express侦听POST请求。如果您希望Express侦听GET请求,则应使用app.get()