Why is my client program not receiving a response from this socket.io server?

Currently, I am in the process of developing a trivia game where two users engage in answering questions with the winner being declared at the end. As part of this project, I have integrated socket.io to facilitate the exchange of answers.

However, I have encountered an issue with my server.js file as it is not functioning correctly. It seems that the allUsershaveAnswered function is failing to trigger upon button press. Additionally, an error message

Failed to load resource: the server responded with a status of 404 (Not Found)
is also popping up, making it challenging for me to pinpoint the root cause.

$(function(){
  var socket =io();

  $('#userIdForm').submit(function () {
    console.log($('#userIdForm').val());
    socket.emit('new user', $('#userIdInput').val());
    $(gameDiv).show();
    $(logInDiv).hide();
    return false;

  });

  // Display a series of questions within the game div
  $('#questionForm').submit(function () {
   socket.emit('answer' , $('#answeredInput').val());
   $('#guessForm').hide();
   $('#questionForm').show();
   return false;
 });
 // Triggered when all users have answered the question

 socket.on('allUsersHaveAnswered', function (msg) {
   $('#resultsDiv').append("The answer was:" + msg.answer + "<br>Winner:"+ msg.winner);
   $('#waitingDiv').hide();
   $('#resultsDiv').show();
 });
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font: 13px Helvetica, Arial;
}

form {
  background: #000;
  padding: 3px;
  position: fixed;
  bottom: 0;
  width: 100%;
}

form input {
  border: 0;
  padding: 10px;
  width: 90%;
  margin-right: .5%;
}

form button {
  width: 9%;
  background: rgb(130, 224, 255);
  border: none;
  padding: 10px;
}

#messages {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

#messages li {
  padding: 5px 10px;
}

#messages li:nth-child(odd) {
  background: #eee;
}
<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <link rel="stylesheet" href="master.css">
  </head>
  <body>
    <div id="logInDiv">
      <h1>Create an Username</h1>
      <form id="userIdForm" action="">
        <input id="userIdInput" autocomplete="off" /><button>Send</button>
      </form>
    </div>
    <div id="gameDiv" hidden>
      <h1 id="info">Answer the General Knowlegde Question</h1>
      <h2 id="info2">Once the other player has answered, you will find out who won!</h2>
      <p>Who won the English Premeier League this year?</p>
      <form id="questionForm" action="">
        <input id="answeredInput" autocomplete="off" /><button>Send</button>
      </form>
      <div id='waitingDiv' hidden>
        <p>Waiting for answers</p>
      </div>
      <div id='resultsDiv' hidden>
      </div>
    </div>
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="./socket.io/socket.io.js"></script>
    <script src="/main.js"></script>

  </body>
</html>

The current setup on the server side looks like this:

// Server Setup 
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;

server.listen(port, function() {
  console.log('Server listening at port %d', port);
});

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

// Provided answer
var answer = "chelsea";

var guessedanswers = {};

io.on("connection", function(socket) {
  socket.on('new user', function(id) {
    socket.userId = id;
  });
  socket.on('guess', function(guess) {
    guesses[socket.userId] = parseInt(guess);
    var numAnswers = Object.keys(guessedanswers).length;
    console.log("we've gotten: " + numAnswers + " guesses");
    if (numAnswers >= 2) {
      var winner = "";
      for (var userId in guessedanswers) {
        var guess = guesses[userId];
        if (guess == answer) {
          winner = userId;
        }
      }

      io.emit('allUsersHaveAnswered', {
        winner: winner,
        answer: "chelsea"
      });
    }
  });
});

Identifying the root cause and resolving it remains my primary concern. Any insights on addressing this issue would be greatly appreciated.

Answer №1

There seems to be a typo in this code snippet:

Object.keys(guessedanswers).lenght

It should actually be .length:

Object.keys(guessedanswers).length

This mistake could be causing the issue where the correct value for numAnswers is not being obtained, preventing the program from entering the if (numAnswers >= 2) condition and therefore skipping the process of io.emit('allUsersHaveAnswers, ...)`.


Regarding the error message

'Failed to load resource: the server responded with a status of 404 (Not Found)'
, it would be helpful to identify the specific resource that is missing. If it is 'main.js', then there may be an issue in your route handling for that particular resource.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to employ a method to eliminate a specific valuable element 'this' from an array?

I am working on a task management app that allows users to create a To-Do list and remove specific items from the list. Currently, I am facing an issue with using 'localStorage' to save the list when the page is refreshed. The problem arises when ...

The sticky navigation bar allows for the overlapping of additional div elements

Here is the HTML AND SCSS(SASS) code for a NAVBAR: <div id="navbar"> <ul> <li><a href="#home">Home</a></li> <li><a href="#main">Main</a></li> ...

An unexpected error occurred in the Angular unit and integration tests, throwing off the script

I seem to be facing a recurring issue while running unit/integration tests for my Angular project using Karma. The tests have a 50:50 success/failure rate, working fine on my machine but failing consistently on our build server, making the process quite un ...

Developing NextJS 13 with App directory integration for socket.io

How do I initialize a socket in the app/api/socket/route.js directory? When referencing the example in the pages/api/socket.js directory, it seems that it does not return an instance of http.ServerResponse. Instead, it returns NextResponse, which does not ...

Updates made to CSS are not appearing on the Joomla site

My website is based on Joomla and has been functioning well since it was created. However, recently I have noticed that any CSS changes made in the files are not showing up on the site. I have tried clearing the cache and viewing it from different ISPs, ...

Retrieving an array from a nested JSON structure using $http.get in combination with mongoose and Node.js

In my possession is a JSON representation of an apartment listing: { "_id": { "$oid": "5673d1dcf93fe452d80c2c2c" }, "street": "myStreet", "buildingNumber": 1, "apartmentNumber": 1, "UsersAndQuestions": [ { ...

Calculate the total value of each individual subject from the checkbox's data-id, presented in a string format and separated by commas

<div> <input type="checkbox" id="Q_1_ck1" value="R" data-id="Environmental Science, Physical Education, Agriculture, Yoga, "> <label class="custom-control-label" for="Q_1_ck1"> ...

Tips for verifying the presence of a 3D model from Spline API within the DOM using Next.js

I am in the process of developing a brand new website and I have integrated a 3D model from spline, although it is taking quite some time to load. To improve user experience, I decided to implement a loader/Spinner. However, I'm facing the challenge o ...

The art of manipulating the position and rotation of A-Frame entities

Unfortunately, my knowledge of positioning and rotating entities in 3D space is limited. Therefore, I am interested in developing a function that simplifies the process by using more intuitive parameters like: createEntity(vertical, horizontal, distance) ...

Submitting multiple files individually using AJAX and formData in a file upload process

Having a form wherein three separate file uploads needs to be done through three distinct file inputs is presenting a challenge. While using AJAX and formData, I've managed to successfully upload the first file, however, subsequent files are not being ...

Is it possible to remove the parent element using CSS?

Is there a method to remove the parent element while retaining the current element? Take a look at my example here: <div id="parent"> <div id="child"> <span>some text</span> </div> </div> div { ...

The for loop is throwing an error because the variable 'i' is not defined

I recently started using eslint and I'm in the process of updating my code to comply with my eslint configuration. module.exports = { env: { browser: true, commonjs: true, node: true, es2021: true, }, extends: 'eslint:recomm ...

I'm working on creating a login page with Bootstrap. Does anyone know the best way to center it on the screen

For a school project, I am working on creating a sign-in page. Although I have come across this code, it does not appear at the center of the page as intended. Instead, the left side displays to the left while the right side shows up to the right. My goal ...

JavaScript, Page Method, and GridView are essential components to creating dynamic and interactive

After learning how to use the page method in JavaScript and ASP.Net (VB.Net), I encountered an issue when trying to insert multiple items into a database using a gridview. Despite my efforts, there were no error messages appearing. Here is what I have so f ...

The footer has a wandering nature, constantly moving around as the wrapper mysteriously vanishes

I understand that this question has been asked multiple times before, but I am struggling to get it right! My goal is to keep the footer at the bottom of the page, but it seems to be acting strangely. Here is my HTML: <!DOCTYPE HTML> <html& ...

Navigating the Foundation Topbar - Should I Toggle?

Is there a simpler way to achieve the navigation I desire, similar to the switcher for uikit? Instead of using data-toggler on each tag in my top bar, is there an easier method where I can click links in my top bar to display different content without go ...

Sending information from the client to the server using AJAX in conjunction with a

My apologies in advance if my English is not perfect. I am currently facing issues with sending data to my ExportServlet using ajax. ExportServlet.java public class ExportServlet extends HttpServlet { private static final long serialVersionUID = 67156058 ...

Retrieve the current date in the format of dd/mm/yyyy using AJAX request

var currentDate = new Date(); var todayDate = currentDate.getDate() + '/' + monthNames[currentDate.getMonth()] + '/' + currentDate.getFullYear(); This is my current date retrieval method. It works well but has a minor issue. For to ...

"Use jQuery to select all the cells in a row except for the

I found a visually appealing table layout that looks like this : https://i.stack.imgur.com/oRxYP.png What caught my attention is how clicking on a row selects the entire row. Take the example in the image above, where the second row is highlighted upon s ...

The class of each page on the website keeps changing, making it a challenge for me to scrape the page descriptions

import requests from bs4 import BeautifulSoup import numpy as np import re import json title = [] pages = np.arange(1,13) for page in pages: url = 'https://www.jobs.ch/en/vacancies/?page='+str(page)+'&term=python%20web' p ...