The requested resource at http://js:port/socket.io/1/ could not be located (Error 404

Having trouble connecting with Socket.io.

This is the server-side code:

function chatserver(){

var express = require('express'),

app = express(),

server = require('http').createServer(app).listen(app.get('port'),function(){

        console.log('Express server listening on port '+ app.get('port'));
    });
var io = require('socket.io').listen(server),
    users = {};

io.sockets.on('connection', function(socket){
    socket.on('new user', function(data, callback){
        if (data in users){
            callback(false);
        } else{
            callback(true);
            socket.nickname = data;
            users[socket.nickname] = socket;
            updateNicknames();
        }
    });

    function updateNicknames(){
        io.sockets.emit('usernames', Object.keys(users));
    }

    socket.on('send message', function(data, callback){
        var msg = data.trim();
        console.log('after trimming message is: ' + msg);
        if(msg.substr(0,3) === '/w '){
            msg = msg.substr(3);
            var ind = msg.indexOf(' ');
            if(ind !== -1){
                var name = msg.substring(0, ind);
                var msg = msg.substring(ind + 1);
                if(name in users){
                    users[name].emit('whisper', {msg: msg, nick: socket.nickname});
                    console.log('message sent is: ' + msg);
                    console.log('Whisper!');
                } else{
                    callback('Error!  Enter a valid user.');
                }
            } else{
                callback('Error!  Please enter a message for your whisper.');
            }
        } else{
            io.sockets.emit('new message', {msg: msg, nick: socket.nickname});
        }
    });

    socket.on('disconnect', function(data){
        if(!socket.nickname) return;
        delete users[socket.nickname];
        updateNicknames();
    });
});
}

This is my HTML script code:

jQuery(function($){

        var socket = io.connect('js/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js');

        var $nickForm = $('#setNick');
        var $nickError = $('#nickError');
        var $nickBox = $('#nickname');
        var $users = $('#users');
        var $messageForm = $('#send-message');
        var $messageBox = $('#message');
        var $chat = $('#chat');

        $nickForm.submit(function(e){
            e.preventDefault();
            socket.emit('new user', $nickBox.val(), function(data){
                if(data){
                    $('#nickWrap').hide();
                    $('#contentWrap').show();
                } else{
                    $nickError.html('That username is already taken!  Try again.');
                }
            });
            $nickBox.val('');
        });

        socket.on('usernames', function(data){
            var html = '';
            for(i=0; i < data.length; i++){
                html += data[i] + '<br/>'
            }
            $users.html(html);
        });

        $messageForm.submit(function(e){
            e.preventDefault();
            socket.emit('send message', $messageBox.val(), function(data){
                $chat.append('<span class="error">' + data + "</span><br/>");
            });
            $messageBox.val('');
        });

        socket.on('new message', function(data){
            $chat.append('<span class="msg"><b>' + data.nick + ': </b>' + data.msg + "</span><br/>");
        });

        socket.on('whisper', function(data){
            $chat.append('<span class="whisper"><b>' + data.nick + ': </b>' + data.msg + "</span><br/>");
        });
    });

Upon initially loading the website everything seems to be working fine. However, when I click on the chat box, an error message appears in the inspect elements/console stating

"GET http://'js':5001/socket.io/1/?.."
. Looking for guidance on how to resolve this issue.

Answer №1

To update the server code, make the following changes:

var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

var io = require('socket.io').listen(server);

If you are using an HTTP server instead of an express.io server, use this:

app.listen(app.get('port'), function(){
   console.log("Express server listening on port " + app.get('port'));
});

Answer №2

Your issue seems to be related to the client-side JQuery script.

var socket = io.connect('js/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js');

The correct way to serve socket.io.js to the client is by changing it to

http://<ip/domain>:<port>/socket.io/socket.io.js

If your Socket.io Server is properly listening to your HTTP server, it will automatically serve the client file via

http://<ip/domain>:<port>/socket.io/socket.io.js
. There is no need to manually copy it to a public folder like resources/js/socket.io.js and serve it that way.

For reference, here's a code sample:
Express 3.x - Express 3 requires you to instantiate a http.Server before attaching socket.io

var express = require('express')
  , http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

//... 

server.listen(8000);

Happy Coding! :)

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

The element is being offset by SVG animation that incorporates transform properties

I'm working on creating a halo effect by rotating an SVG circular element using the transform rotate function. I've been using getBox to find the center point of the element, but when the rotation occurs, the overall image is getting misaligned w ...

Nuxt - Issue persisting logged in state on refresh despite information being stored in local storage and cookies

I am facing an issue where the state gets cleared on refresh, even though the token, userid, user email, and expiration date are stored in local storage and cookies. I suspect there might be a problem with the store or something else needs to be done to re ...

What is the best way to filter out empty arrays when executing a multiple get request in MongoDB containing a mix of strings and numbers?

I am currently working on a solution that involves the following code: export const ProductsByFilter = async (req, res) => { const {a, b, c} = req.query let query = {} if (a) { query.a = a; } if (b) { query.b = b; } if (c) { ...

Unable to access image from JSON within Mobile Angular Ui utilizing Angular Js

Currently, I am able to retrieve various data from JSON such as Price and Display Order, but I am facing difficulty in fetching the image. HTML: <div ng-controller="chooseProductDescription"> <div ng-repeat="cat in productDescrip ...

Tips for organizing a search using two keys in Javascript

I am dealing with a large dataset containing over ten thousand objects that hold information about two different ids as shown below: dataSet = [ { ids: ["123", "234"], information: 1 }, { ids: ["123", "345"], in ...

Is there a navigation feature in VueJS that functions similarly to React Router?

I am currently working on enhancing the navigation experience of an existing vueJS application that utilizes Vue Router. When working with React, I typically structure breadcrumbs in the following manner: <Breadcrumbs> <Route path="/users&q ...

Is there a way to make text within a Div selectable even if it is positioned behind another Div with a higher z-index?

Currently grappling with some code, unfortunately cannot easily paste the problematic part here as I am unsure of its exact location. Here's the situation: there is a div containing text that needs to be selectable, however, there is another div with ...

The error message "Uncaught TypeError: res.sendStatus is not a function" was encountered

I encountered a peculiar issue within my application. Upon inspecting the package.json, it reveals that the version of express is set to be greater than 4.x. { "name": "MyAPI", "version": "1.0.0", "private": true, "scripts": { "start": "node . ...

Utilizing Rvest for extracting data from LinkedIn profiles

I've been trying to scrape my LinkedIn profile using Rvest, but I encountered a problem in the experience section. The XPath below was supposed to retrieve the experience section, but it's returning 0 nodes: Test <- read %>% html_nodes(xpath = & ...

Invoke `setState` function in contexts outside of React framework

Is the following approach guaranteed to work correctly within React v18 semantics? The "rules of hooks" only address calling the hook within the component, with no mention of whether it's acceptable to call the dispatcher returned from the ...

I am having difficulty with my JavaScript code not being able to interpret the JSON output from my PHP code. Can anyone help me troubleshoot

Having trouble working with an AJAX call and handling the JSON object it generates in JavaScript? Here's a sample snippet of PHP code returning the JSON object: echo json_encode(array("results" => array(array("user" => $member['user'] ...

HTTPS is causing issues with the functionality of the API route

I currently have a node server running on port 3000 specifically to handle api requests. Everything seems to be functioning fine as expected... However, when I try accessing this, it doesn't seem to work. Could someone possibly shed some light on w ...

Is the presence of an excessive number of arguments in the object that includes functions an instance

In my program, I have implemented a feature where the user can provide an array to determine which functions are executed in a loop. However, managing the list of variables that need to be passed into each function has become challenging as the list keeps ...

How to circumvent an email forwarder that removes attributes from an image tag and still track email opens?

While it may seem like an impossible task, I decided to give it a try. If the service I am utilizing removes the attributes of an image tag =>, is there a workaround available? I attempted inserting random unicode characters to disrupt the parser, but unf ...

Detecting errors in asynchronous functions within other asynchronous functions

I'm attempting to capture errors in nested asynchronous functions to perform a rollback if an error occurs. Initially, I have a try-catch block where I call a function that then calls another function. The final function should throw an error, and I ...

What is the reference point for 'this' in Mongoose query middleware and pre-find hooks?

After diving into the world of mongoose query middleware, I've come to realize that using this within a query middleware function actually refers to the query object itself. Despite this knowledge, I still find it challenging to imagine what the quer ...

Using PHP to extract all occurrences of window.location from an HTML document using regex

Is there a way to extract all the window.location instances in PHP? I have a list of URLs that I am fetching using cURL, saving the HTML content as a string, and now I need to identify and display all the occurrences of window.location separately. I atte ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

Changing a button's value on click using PhoneGap

I've been working with phonegap and came across an issue with my buttons setup like this: <input id="my_button" type="button" onclick="my_function();"/> The goal is to capture the click event and change the button's value, my_function ( ...

Searching for a method to locate and substitute a specific HTML string using the `sed` command in the macOS Catalina terminal

I am attempting to modify the following html code: <svg xmlns="http://www.w3.org/2000/svg" width="20" viewBox="0 0 256 256"> to this updated version: <svg xmlns="http://www.w3.org/2000/svg" width="30&q ...