0

I'm trying to figure out how to create a real time chat application that uses Vue.js for the front-end, Node.js for the back-end and socket.io.

I've generated my back-end Node.js project with express-generator and the project is accessible at http://localhost:3000. In this project I have an index.js file that contains this:

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

io.on('connection', (socket) => {
    console.log('a user connected');
});

My front-end is a Vue.js project accessible from http://localhost:8080 and the component that is meant to connect to my back-end contains this:

<template>
    <div class="home">
        Hello
    </div>
</template>

<script>
import socket from 'socket.io-client'

export default {
    mounted(){
        socket.connect('http://localhost:3000')
    }
}

</script>

Sadly the socket connection doesn't seem to go through. On the front-end console I get these errors -

Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=3&transport=polling&t=N6JFKSo' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
polling-xhr.js?d33e:268 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=N6JFKSo net::ERR_FAILED

And on the back-end console I get errors like this one - GET /socket.io/?EIO=3&transport=polling&t=N6JFrfo 404 5.289 ms - 975

I can't figure out why is this happening.

halfer
  • 19,824
  • 17
  • 99
  • 186
Onyx
  • 5,186
  • 8
  • 39
  • 86
  • Have you enabled cors on the backend service? – Suresh Prajapati Apr 19 '20 at 16:28
  • Take a look at this article: https://daveceddia.com/access-control-allow-origin-cors-errors-in-angular/ – ecrb Apr 19 '20 at 16:29
  • On your node js server add the cors module. // npm install --save cors and then add this to your code : const cors = require('cors'); app.use(cors()); – Node_Ninja Apr 19 '20 at 16:33
  • I did that but nothing changed. I'm surely doing something wrong since I just recently started using Node.js instead of Laravel but I just can't figure out what. – Onyx Apr 19 '20 at 16:50

1 Answers1

0

In index.js, add the following line below your important for socket.io:

io.origins('localhost:8080')

or if you want it for any domain:

io.origins('*:*')

Source

Saddy
  • 1,515
  • 1
  • 9
  • 20
  • I did tried the solutions on the question you linked but they didn't work for me and still don't. – Onyx Apr 19 '20 at 16:32
  • Interesting, have you tried setting the headers like shown here: https://stackoverflow.com/a/54309080/8993539 – Saddy Apr 19 '20 at 16:33