Unlocking the secrets to obtaining a socket.io client

I encountered an error when trying to set up a socket.io server and client. The error I received on the client side was:

Failed to load resource:http://localhost:3000/socket.io/?EIO=4&transport=polling&t=OK-egu3 the server responded with a status of 404 (Not Found)

Server.js code:

const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {cors: {origin: "*"}});
const path = require('path');

app.set('view engine', 'ejs');

app.use(express.json({extended: true, limit: '1mb'}));

io.on('connection', (socket) => {
 console.log("new connection " + socket);
});

app.get("/", (req, res, next) => {
 res.render('index'/*, { ioS : io }*/);
});

console.log("Ready");

app.listen(3000);

Index.ejs code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>socket Respons</h1>
</body>
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js" integrity="sha384-/KNQL8Nu5gCHLqwqfQjA689Hhoqgi2S84SNUxC3roTe4EhJ9AfLkp8QiQcU8AMzI" crossorigin="anonymous"></script>
<script>
    //const io = ;
    const socket = io();
    console.log(socket);
</script>
</html>

The libraries I have installed are:

- socket.io - socket.io-client - express - ejs

Answer №1

Your client initialization is incomplete. The server is on localhost:3000, but the client is unaware of this because you have not specified where to connect.

If we refer to the official socketio documentation, it suggests providing the URL of the server's socket endpoint like so:

const URL = "http://localhost:3000";
const socket = io(URL, { autoConnect: false });

The error message stating "not found" may seem vague, but it does provide a clue for debugging purposes.

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

Trouble with Bootstrap Collapse feature not collapsing on its own

I recently added a Bootstrap collapse feature to my payment view in Laravel. The Bootstrap section collapses when clicked, but I would like it to be collapsed by default. I understand that I need to include: aria-expanded="false" However, it still doesn& ...

Prevent access to URLs that do not match a certain pattern in Chrome

I will be implementing a filter to block request URLs that do not match a specific pattern. To achieve this, you can utilize the request blocking feature within Google Chrome's network tab. Simply right click on the request Row and select "block requ ...

Utilize Vuex mutators within route navigation guards

Hey there, I'm currently working on an app using Laravel and VueJS. To restrict certain routes, I've implemented navigation guards. However, I'm facing an issue where I need to access Vuex mutators to determine if the current user is logged ...

Exploring JSON data with ReactJS

I am experiencing issues with populating a table with data imported from a JSON file. The error message I'm receiving is: Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {list}). If you intended to render ...

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, ...

What is the best way to pass parameters using query or route in a form?

form(action='/allusers', method="post") input(id='name', placeholder='First Name / Last name') button(type='submit') Launch Spacecraft In my HTML (Jade) code, I am trying to redirect to the allusers page ...

Executing JavaScript following an Ajax request

I am faced with a situation where my HTML file utilizes a function for loading another PHP file using Ajax: function LoadContent(n,func) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xm ...

The difference between emitting and passing functions as props in Vue

Imagine having a versatile button component that is utilized in various other components. Instead of tying the child components to specific functionalities triggered by this button, you want to keep those logics flexible and customizable within each compon ...

Enhance TinyMCE functionality to permit text as a primary element within <table> or <tr> tags

I've been struggling for the past three hours, trying out different solutions and searching like crazy on Google. Unfortunately, I have not been able to find a resolution to this particular issue. Issue: TinyMCE is not allowing me to insert text dire ...

Displaying success and failure messages on a modal window using Ajax in PHP form

Unable to display error messages or success messages in the same modal window. I have set up Wordpress and using the following code: Form <form id="formcotizador" method="post" action="<?php echo get_template_directory_uri(); ?>/cotizador/procc ...

Why is the Javascript code outputting undefined and NaN during execution?

As a newcomer to the world of javascript, I am venturing into learning its fundamental concepts. In my quest for knowledge, I've dabbled in file reading and came up with a small script which you can find below. // Incorporating the fs (filesystem) mo ...

Utilizing NodeJS express for routing with a designated router strategy

I recently set up a node project using the express generator Here is the main app.js file: var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require(&a ...

What steps can I take to resolve my password validation rule when confirming during sign-up?

Utilizing react-hook-form in combination with Material-UI for my sign-up form has been a challenge. I am currently working on implementing a second password field to confirm and validate that the user accurately entered their password in the initial field, ...

Ways to verify the element prior to the completion of the request?

Utilizing Angular and Playwright Within my application, I have incorporated 2 buttons - one for delete mode and another for refreshing. Whenever the user triggers a refresh action, the delete mode button is disabled. Once the request returns, the delete m ...

Is it acceptable to use JavaScript files in the pages directory in NEXTJS13, or is it strongly advised to only use TypeScript files in the most recent version?

In the previous iterations of nextJS, there were JavaScript files in the app directory; however, in the most recent version, TypeScript files have taken their place. Is it still possible to begin development using JavaScript? I am working on creating an a ...

Tap the <li> element in a select2 dropdown from Bootstrap using internjs

I am currently encountering an issue while trying to select values from a Bootstrap-select2 drop-down in my form during the process of writing some function tests. If Select2 is unfamiliar to you, here are some examples that may help: The drop-downs are ...

Is Express the best choice for my straightforward messaging platform?

I'm currently in the process of developing a basic chat client that will establish connections with a Node.js server using Socket.io websockets. Here is a simplified version of my client-side JavaScript code: socket = io.connect('http://localho ...

Converting objects into CSV format and exporting them using JavaScript

When exporting to CSV, large strings are causing other cells to be rewritten. See the screenshot for the result of the export here. For the code related to this issue, refer to this link. The question is how to prevent large string values in a cell from a ...

Restarting a JavaScript function upon switching views in Vue.js

I am new to working with Vue.js and I have a Laravel app that utilizes it. One issue I am facing is that when the homepage is loading, all elements like owl carousel and rev slider are initialized. However, if I navigate to other routes such as contact or ...

When attempting to access an API hosted on Cloudflare from Heroku, a 403 error is returned

I am currently utilizing the Cowin API () to access available slots. My implementation is based on Node.js. Interestingly, it functions well on my local machine but encounters an error after deployment on Heroku. 2021-05-09T11:07:00.862504+00:00 app[web.1] ...