how to use socket.io with two files?

Viewed 188

I have a problem with Socket.io, I use express and I want two .html files that can send messages to the server. But one of two files send an error:

Failed to load resource: net::ERR_FILE_NOT_FOUND
add.html:26 Uncaught ReferenceError: io is not defined
    at add.html:26

Here my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aggiungi una storia</title>
</head>
<body>
    <!--!link-->
    <p class="i_link">Storia:</p>
    <textarea name="link" id="Story_Text" cols="100" rows="20"></textarea><br>
    <!--!name-->
    <p class="i_name">Nome:</p>
    <textarea name="name" id="Story_Name" cols="50" rows="1"></textarea><br>
    <!--!number-->
    <p class="i_number">Numero Atto:</p>
    <textarea name="number" id="Story_Number" cols="1" rows="1"></textarea><br>
    <!--!author-->
    <p class="i_author">Autore:</p>
    <textarea name="author" id="Story_Author" cols="50" rows="1"></textarea><br>
    <button onclick="myFunction()">Click me</button>
​
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();

function myFunction() {
    let link = $('#Story_Text').val();
    let number = $('#Story_Number').val();
    let author = $('#Story_Author').val();
    let name = $('#Story_Name').val();
    console.log(link + number + author + name)
}
</script>
</body>
</html>

How I can resolve this?

Thanks in advance and sorry for the bad English!

3 Answers

Did you install socket.io ? npm install socket.io

It seems your reference to the "Socket.io" js file isn't correct.

<script src="/socket.io/socket.io.js"></script> <!-- here -->

Please make sure it points to the correct file, check the browser network tab to see if the script is correctly loaded. When it is, the 'io' function will be available

It seems like it cannot find the file /socket.io/socket.io.js

https://socket.io/docs/v3/client-installation/#Installation

By default, the Socket.IO server exposes a client bundle at /socket.io/socket.io.js.

Do you have the server running? Otherwise you could try the cdn path to see if that works:

<script src="https://cdn.socket.io/socket.io-3.0.1.min.js"></script>
Related