socket.io cors error . i try to connect socket.io in laravel vuejs but cors error getting

Published

Access to XMLHttpRequest at ‘http://dolphin.test:3001/socket.io/?EIO=4&transport=polling&t=Ni7Nzha’ from origin ‘http://dolphin.test’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

i try to connect socket.io in vuejs but code give me cors error

Server side code :->

const express = require('express');
const app = express();
var https = require('https');
var http = require('http');
const axios = require('axios'); 
const fs = require('fs');
var cors = require('cors');
app.use(cors());

const options = {};
const server = http.Server(app);

const io = require('socket.io')(server);
server.listen(3001,function(){
    console.log('server running on port 3001');
});

var clients = {};
var connected_users = [];


io.on('connection', function(socket) {
 console.log("connection establish");
  socket.send('Hello!');
  socket.on('add-user', function(data) {
    clients[data.userId] = {
     "socket": socket.id,
   };
  connected_users.push(data.userId);
  io.sockets.emit('connected-users', { users_connected: connected_users });
});

socket.on('chat-message', function(data){
  if (clients[data.user_id]) {
    io.sockets.connected[clients[data.user_id].socket].emit("chat-message", data);
    // console.log(data);
  } else {
    console.log("User does not exist: ");         
  }
});

//Removing the socket on disconnect
socket.on('disconnect', function() {
 for(var name in clients) {
  if(clients[name].socket === socket.id) {
    delete clients[name];
    break;
  }
 }  
})
});

Client side code :->

import io  from 'socket.io-client';
export default {
    data() {
        return {
            isActive : '',
            activeId : '' ,
            isImageLoaded : false,
            user : {},
            src : '',
            siteSettings : {},
            form: new Form(),
            socket : io("http://dolphin.test:3001"),  
        }
    },
    async created() {
        this.showData();
        
        this.socket.on('connection', (socket) => {
            console.log('Admin user connected');
            // socket.on('disconnect', () => {
            //     console.log('user disconnected');
            // });
        });
         this.socket.on('add-user', function (data) {
             console.log(data);
        });
    },

Source: Laravel

Published
Categorised as laravel, node.js, socket.io, vue.js Tagged , , ,

Answers

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq