简体   繁体   中英

Nodejs, express, Ajax: Function triggers only Six Times

using nodejs and express I'm trying to trigger a js function which contains a simple console log. Sadly the function only triggers 6 times and freezes for a while. After a minute or two all the button clicks which where clicked during the "frozen time" triggers at once. It happens always after 6 times of pressing a button.

index.html -> button
client side -> jquery function that triggers an Ajax post function
server.js -> contains the express function which triggers the console log

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');

});

What am I doing wrong? Any tips how I can improve my code?

Thank You

Your server needs to respond to the request. Try updating your server to:

var app = express();

app.post('/drive', function(req, res){

   console.log('Car starts driving');
   res.sendStatus(200)

});

This will return 200 OK to all requests.

Why does this happen after 6 requests? I'm guessing you're using Chrome or Firefox. Chrome and Firefox will only allow a maximum of 6 concurrent requests to a single server. Once you reach 6, the browser will queue the remaining requests.

The reason your seeing it fix itself after a while is due to the request timeout. Once the request has timed out (because it has received no response), the browser will close the connection.

Browser concurrent request per host limits - https://stackoverflow.com/a/985704/4774345

Your server code should return statement:

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

sendStatus details

Good practice is to disable the button after clicking, and then enable it after the response comes back:

//Disable button

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

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

You need to send it asynchronous.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM