Endemic
Endemic

Reputation: 370

Socket.io client responds only once

I am creating an express server which will cause the index.html page to redirect to a new page on receiving a post request. Everything works fine, but only for the first time. I have to restart the server regularly for it to work. Here are some code snippets.

//server.js

const app = express();
app.use(express.static(`${__dirname}/public`));

const server = http.createServer(app);
const io = socketIo(server, {'force new connection': true });

io.on('connection', (socket) => {
    console.log('New client connected');

    app.post('/redirect', (req,res) => {
        socket.emit('redirect');
        res.status(200).send('Redirected');
    });
});
<body>

   <!-- Jquery CDN -->
   <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
   <!-- Socket.IO -->
   <script src="/socket.io/socket.io.js"></script>

   <script>
   let socket = io.connect({'force new   connection': true });
   socket.on('connect', () => {
       console.log('Connected to Server');
   });

   socket.on('redirect', () => {
       window.location.replace("https://google.com");
   });
   </script>

</body>

Upvotes: 0

Views: 1437

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40394

The main issue, is that you have your route inside the socket connection listener. A route should be only registered once. And connection is triggered multiple times.

const app = express();
app.use(express.static(`${__dirname}/public`));

const server = http.createServer(app);
const io = socketIo(server, {'force new connection': true });

app.post('/redirect', (req,res) => {
    res.status(200).send('Redirected');
    io.emit('redirect');
    // io.to(someSocketOrRoom).emit('redirect');

});

io.on('connection', (socket) => {
    console.log('New client connected');     
});

If you want to emit to the socket when you receive a message from outside the socket, in this case an HTTP Post. You need to use io.emit to emit to all sockets, or io.to().emit to emit to a specific one.

Now, it doesn't make much sense to redirect using socket.io, if you're posting to /redirect why don't you just redirect the user using res.redirect, without emitting anything.

Upvotes: 1

Related Questions