javascript – How to configure socket.io to listen to client side-ThrowExceptions

Exception or error:

I am new to using sockets and do not fully understand how they work.

When i load my website I get this error I just get this error “chat.js:4563 GET http://localhost/socket.io/?EIO=3&transport=polling&t=N3Jn3vr 404 (Not Found)”

What am I missing? I am assuming I have to make the two ports work with one another somehow?

socket.js file:

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

http.listen(3000, function(){
  console.log('listening on *:3000');
});

io.on('connection', function(socket){
  socket.on('chat.message', function(message) {
     console.log('x: ' +  message)
  })
});

chat.js file:

import io from 'socket.io-client';

const socket = io('http://localhost:80');

var app = new Vue({
    el: '#app',
    mounted() {
    },
    data: {
      message: null
    },
    methods: {
        send() {
            socket.emit('chat.message', this.message)
    }
}})

blade file:

@extends('dashboard.base')

@section('content')

    <div class="container-fluid">
        <div class="fade-in">
            <div class="row">
                <div class="card mx-auto text-center w-50">
                    <div  class="card-header">
                        Live Chat
                    </div>
                    <div id="app" class="card-body">
                        <input v-model="message" type="text">
                        <span class="btn btn-success" @click="send">Send</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

@endsection

@section('javascript')
    <script src="{{ mix('js/chat.js') }}"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
@endsection

How to solve:

As both express and socket.io are using http they will share the same port. So you should listen to socket connections on port 3000 instead of port 80.

You could just initialize the socket object with io without the url, as it’s on the same port as your express app. Socket.io will connect to the same host that serves the page

const socket = io();

The getting started page here gives an overview of the same.

Leave a Reply

Your email address will not be published. Required fields are marked *