nitish
nitish

Reputation: 111

socket.io client is giving cros error in ionic application

I am trying to implement a chat application using node.js socket.io and ionic 4 but I am getting cros policy error on client side

This is my node.js server

const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const {Users} = require('./utils/users');
const publicPath = path.join(__dirname, '../public');
const port = process.env.PORT || 3000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
var users = new Users();
app.use(express.static(publicPath));
app.use( (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "http://localhost:8100"); //The ionic server
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
io.on('connection', (socket) => {
  console.log('New user connected', socket.id);
    socket.on('setName', function (data) {
      console.log(data);
      socket.id = data.name;
  });

Here is my ionic client I am using ngx-socket-io plugin for socket.io client.

import { Component } from "@angular/core";
import { Router } from "@angular/router";
import { NavController } from "@ionic/angular";
import { Socket } from "ngx-socket-io";
@Component({
  selector: "app-home",
  templateUrl: "home.page.html",
  styleUrls: ["home.page.scss"]
})
export class HomePage {

      constructor(
    private router: Router,
    private navCtrl: NavController,
    private api: ApiService,
    private socket: Socket

  ) {
       this.socket.connect();
    this.socket.emit("createMessage", "from ionic ");
    }
}

This is my socketIO configuration on app module

import { SocketIoModule, SocketIoConfig } from "ngx-socket-io";
const config: SocketIoConfig = {
  url: "https://appName.herokuapp.com/",
  options: {}
};

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    SocketIoModule.forRoot(config),
    IonicStorageModule.forRoot(),
    IonicModule.forRoot(),

This is the error I am getting

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

Upvotes: 2

Views: 1993

Answers (1)

Falyoun
Falyoun

Reputation: 3976

Try the following

app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8100');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});

If it does not work,Try using CORS package,

To install it npm install cors --save

For using:

const cors = require("cors"); 
const corsOptions = { 
   origin: "*", 
   credentials: true 
};
app.use(cors(corsOptions)); 

Upvotes: 1

Related Questions