I just started using socket.io on my node.js-server. I just want to emit an event whenever I do a post request to the server via clicking on a button. The problem is that the event is already being emitted when I load the page and then will be emitted every two minutes again. Why is this happening and how can I prevent this? I just want the event to be fired once after I clicked on the button.
server.js
const express = require('express')
const app = express()
const server = require('http').createServer(app)
const io = require('socket.io')(server)
app.post('/event', function (req, res, next) {
console.log('emit event')
io.emit('event')
})
app.use(express.static(__dirname + '/public'))
server.listen(8085)
index.html
<html>
<body>
<div class="container">
</div>
<button type="submit" id="fire">Fire!</button>
<script src="/socket.io/socket.io.js"></script>
<script src="jquery-3.2.1.js"></script>
<script src="index.js"></script>
</body>
</html>
index.js
$('#fire').on('click', function () {
console.log('fire!')
$.ajax({
url: '/event',
method: 'POST'
}).done(function (data) {
console.log('done')
alert(data)
}).fail(function (data) {
console.log('fail')
alert(data)
})
})
$(function () {
var socket = io.connect('http://localhost:8085')
var container = $('.container')
socket.on('event', function (bcevent) {
console.log('got event')
var newItem = '<p>EVENT</p>'
container.append(newItem)
})
var jqxhr = $.post('/event', function () {
// alert( "success" );
})
.done(function () {
// alert( "second success" );
})
.fail(function () {
// alert( "error" );
})
.always(function () {
// alert( "finished" );
})
})
Thank you very much for your time and efforts.
via Mr. T
No comments:
Post a Comment