Nodejs,express,Ajax:函数只触发六次

使用nodejs和expression我试图触发一个js函数,其中包含一个简单的控制台日志。 可悲的是,这个函数只触发了6次,并冻结了一段时间。 一两分钟后,所有在“冻结时间”点击的button点击一次触发。 它总是在按下button6次后发生。

index.html – >button
客户端 – > jquery函数触发一个Ajax post函数
server.js – >包含触发控制台日志的express函数

的index.html

<input type="button" id="car" value="drive"/> 

clientside.js

 $('#car').click(function(){ $.ajax({ type:'POST', url: url + '/drive' }); }); 

server.js

 var app = express(); app.post('/drive', function(req, res){ console.log('Car starts driving'); }); 

我究竟做错了什么? 任何提示如何我可以改善我的代码?

谢谢

您的服务器需要响应请求。 尝试更新您的服务器:

 var app = express(); app.post('/drive', function(req, res){ console.log('Car starts driving'); res.sendStatus(200) }); 

这将返回200 OK到所有请求。

为什么在6次请求后发生这种情况? 我猜你正在使用Chrome或Firefox。 Chrome和Firefox将只允许一个服务器的最多6个并发请求。 一旦你达到6,浏览器将排队剩余的请求。

之所以你看到它自己修复一段时间是由于请求超时。 一旦请求超时(因为它没有收到响应),浏览器将closures连接。

按主机限制浏览器并发请求 – https://stackoverflow.com/a/985704/4774345

 $('#car').click(function(){ $.ajax({ type:'POST', async : true, url: url + '/drive' }); 

你需要发送asynchronous。

你的服务器代码应该返回语句:

 app.post('/drive', function(req, res){ console.log('Car starts driving'); res.sendStatus(sendStatus) }); 

sendStatus详细信息

好的做法是在单击后禁用button,然后在响应返回后启用它:

//停用button

 $.ajax({ url: url + '/drive' type: 'POST', data: {}, success: function(data){ //Enable button }, error: function(data){ //Enable button } });