1

I am trying to make a basic counter that works between browsers/computers. (I'm new at this). The button only works about 1/12th of the time. How do I make it more consistent?

Thanks!

My server side node.js looks like:

var express = require('express');
var app = express();
var hits = 0;

app.get('/main.html', function (req, res, next) {
    console.log('bye');
    next();
});

app.get('/', function (req, res, next) {
    console.log('hello');
    next();
});

app.get('/add', function (req, res) {
    console.log('added hits');
    hits++;
});

app.get('/hitNum', function (req, res) {
    console.log('hits req');
    res.end(hits+'');
});

app.use(express.static(__dirname + '/public'));

var server = app.listen(80);

My HTML looks like:

<!DOCTYPE html>
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>     
        <script>
            var add = function () {
                $.get('add');
            }

            window.setInterval(function (){
                $.get('hitNum').done(function (data){
                    document.getElementById('hits').innerText = data;
                }); 
            }, 500);

        </script>
    </head>
    <body>
        <button onclick='add()' >Hi</button>
        <p id='hits'></p>   
    </body>
</html>

1 Answer 1

1

I would start by changing the /hitNum controller: Instead of just calling end() it is preferred to explicitly set the status and the body (via status() and send(), respectively). Here's how I'd write it:

app.get('/hitNum', function (req, res) {
    console.log('hits req');
    res.status(200).send('' + hits);
});

the 200 status indicates "SUCCESS".

One more thing:

Your /add controller does not send any response back. This means that your JS will not know if/when the /add request has been completed:

app.get('/add', function (req, res) {
  console.log('added hits');
  hits++;
  res.status(200).end();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.