Search code examples
node.jsangularsocket.iocors

Socket io communication blocked by CORS policy in a Node js + Angular application


So I use a simple node.js server with express and socket.io When I try to communicate with a simple client written in javascript, it works perfectly, but when I try to create the communication with an Angular app (using ngx-socket-io), I get the following error message :

Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=NQFEnVV' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This is the nodejs server :

var express = require('express');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 5000;
app.set(port, process.env.PORT);
app.use(express.static('./client/'));

io.on('connection', socket => {
    socket.emit('connection', 'data from server!');
});
 
http.listen(port, () => {
    console.log('App listening on port ' + port);
});

And this is how I implement socket.io on Angular client :

app.module.ts :

import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';

const hostname = window.location.hostname;
const url = (hostname === 'localhost') ? `${window.location.protocol}//${hostname}:5000` : undefined;
const config: SocketIoConfig = { url, options: {} };

@NgModule({
  declarations: [...],
  imports: [
    ...
    SocketIoModule.forRoot(config)

class that use socket io :

constructor(private socket: Socket) { }

    this.socket.on('connection', (data) => {
      console.log('Working ' + data);
    });

I tried to fix the CORS error with headers in server side such as :

const io = require('socket.io')(server, {
  cors: {
    origin: '*',
  }
});

or

app.use(function(request, response, next) {
     response.header("Access-Control-Allow-Origin", "*");
     response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
     next();
});

but it still display the same error.

I use of course the command ng serve to run my application (running on port 4200) and it was perfectly working 3 months ago. (Working with the ng serve, and the ng build prod as well).


Solution

  • Verify socket.io-client version on the angular packaje.json file. If it's lower than 3.1.2 you could try to upgrade it by npm install [email protected] --save Also you could verify the serverside once again looking at this

    const app = require('express')();
    const http = require('http').createServer(app);
    const io = require('socket.io')(http, {
        cors: {
            origins: ['http://localhost:4200']
        }
    });
    

    Replace http://localhost:4200 by your current environmment on the Angular App