[英]How do I prevent socket.io from emitting events sequentially/automatically?
我剛剛開始在我的node.js服務器上使用socket.io。 我只想在通過單擊按鈕向服務器發出發布請求時發出事件。 問題在於,當我加載頁面時已經發出了該事件,然后每兩分鍾將再次發出該事件。 為什么會發生這種情況,我該如何預防呢? 我只希望單擊按鈕后將事件觸發一次。
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" );
})
})
非常感謝您的時間和精力。
問題是兩件事的結果:
您在頁面加載時發出請求:
var jqxhr = $ .post('/ event',function(){
某些瀏覽器(包括Chrome)如果失敗或不返回,可能每兩分鍾重試一次請求。 確保服務器中沒有斷點,並且服務器發送的響應代碼為200。
您的端點不向客戶端返回任何內容。 在這種情況下,某些瀏覽器會重試該請求。
確保在發出事件后將一些結果返回給客戶端,例如:
app.post('/event', function (req, res, next) {
console.log('emit event');
io.emit('event');
res.status(200).send();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.