express – Node.js – Socket.io not emiting

I’m learning about socket.io and real-time interactions between client and server.
Said that, the project that I’m trying to create for my portofolio is a chat-app.

The problem that I’m facing is that Client (chat.js) is not Emiting.

index.html

<!DOCTYPE html>
<html>
    <head>
    
    </head>
    <body>
        Chat App
        <button id="increment" onclick="buttonClicked()">+1</button>
        <script src="/socket.io/socket.io.js"></script>
        <script src="./js/chat.js"> </script>
    </body>

</html>

index.js (server)

const path = require("path")
const express = require("express")
const http = require("http")
require("dotenv").config()
const Server = require("socket.io")


const app = express()
const server = http.createServer(app);
const io = new Server(server)
const port = process.env.PORT
const public_directory = path.join(__dirname, "../public")

app.use(express.static(public_directory))

io.on("connection", (socket)=>{
    console.log("User Connected")
    socket.on("Button", (number)=>{
        console.log("Message: " + str(number))
    })
})

server.listen(port, ()=>{
    console.log(`Listening on port : ${port} `)
})

chat.js

const socket = io()


function buttonClicked(){
    console.log("+ 1")
    socket.emit("Button", 1)
}

When I’m connected I receive the message User Connected, so the connection is well established.

Read more here: Source link