Socket IO not defined

Halo saya sedang belajar di

https://sekolahkoding.com/kelas/membuat-aplikasi-chat-dengan-nodejs, tapi saat di tengah" ada kendala error seperti

io is not defined

ok kata mas hilman kita butuh socket io untuk client yang berisi

<script src="/socket.io/socket.io.js"></script>

tapi saat saya run lagi server nya trnyata error nya masih sama

ini full code nya:

server.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html')
})

io.on('connection', function(socket){
    socket.on('newMessage', function(msg){
        io.emit('newMessage', msg)
        console.log('Chat baru: ' + msg);
    })

    socket.on('disconnect', function(msg){
        console.log('user disconnected');
    })
})

app.listen(3000, function(){
    console.log('Listening on 3000');
})

index.html

<!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>Socket IO Node JS</title>
</head>
<style>
    form{
    position: absolute;
    bottom: 0px;
    width: 100%;
    background: grey;
    padding: 20px;
}

input{
    float: left;
    width: 70%;
    height: 30px;
    border: none;
}

button{
    float: left;
    width: 20%;
    height: 33px;
}
</style>
<body>
    <ul id="messages"></ul>

    <form>
        <input type="text" id="text_box">
        <button>Kirim</button>
    </form>
</body>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
    var socket = io();

    $('form').submit(function(e){
        socket.emit('newMessage', $('#text_box').val())
        $('#text_box').val('')

        return false
    })

    socket.on('newMessage', function(msg){
        $('#messages').append($('<li>').text(msg))
    })
</script>
</html>

dan ini package.json

{
  "name": "chat-nodejs",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.3",
    "socket.io": "^4.4.1"
  }
}

express dan socket io sudah saya install jadi seharusnya tak ada masalah, saya lihat di dokumentasi socket.io juga sama saja caranya

avatar yunianrezky
@yunianrezky

28 Kontribusi 10 Poin

Dipost 2 tahun yang lalu

Belum ada Jawaban. Jadi yang pertama Jawaban

Login untuk ikut Jawaban