Danish Sarwar
Danish Sarwar

Reputation: 403

Socket.io and node JS resulting CORS blocked issue

I've been working on chat functionality. There are two kinds of clients, One is the frontend of my application and the second is random another website. I know there are plenty of issues like this but I tried all of the solution but I'm still getting following error:

Access to XMLHttpRequest at 'https://mydomain/socket.io/?EIO=3&transport=polling&t=NCjoM1w' from origin 'null' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

and this the error I'm getting on client-side of my own front end:

https://mydomain/socket.io/?EIO=3&transport=polling&t=NCjnJUX 404 (Not Found)

This is how I'm trying to connect from client-side.

    var socket = io.connect("https://mydomain:443/", {secure: true, port: '443'});

and this is my server.js code

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const base = require("./routes/api/base");
const leads = require("./routes/api/leads");
const requests = require("./routes/api/requests");
const offApp = require("./routes/api/offApp");
const chat = require("./routes/api/chat");
const chatSocket = require("./routes/socket/chat");
const path = require("path"); // on top
const app = express();
// const client = require('socket.io').listen(4000).sockets;
const https = require('https');
const fs = require('fs');

var options = {
  pfx: fs.readFileSync('certificate.pfx'),
  passphrase: 'password'
};

app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, *');
  next();
});

var server = https.createServer(options, app);
var client = require("socket.io").listen(server);
client.origins('*:*') ;
server.listen(443);

// Bodyparser middleware
app.use(
  bodyParser.urlencoded({
    extended: false
  })
);
app.use(bodyParser.json());

// DB Config
const db = require("./config/keys").mongoURI;

// Connect to MongoDB
mongoose
  .connect(
    db,
    { useNewUrlParser: true }, (err, db) => {

      if (err) {
        throw err;
      }
      console.log('MongoDB connected');
      chatSocket(db, client);
    });

// Passport middleware
app.use(passport.initialize());

// Passport config
require("./config/passport")(passport);

// Routes
app.use("/api/users", users);
app.use("/api/base", base);
app.use("/api/leads", leads);
app.use("/api/requests", requests);
app.use("/api/offapp", offApp);
app.use("/api/chat", chat);

const port = process.env.PORT || 5000;

app.use(express.static("client/build")); // change this if your dir structure is different
app.get("*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});

app.listen(port, () => console.log(`Server up and running on port ${port} !`));

Please help me resolve this CORS and other issues. I am using the Azure app service. That's why I can't use any other port than 80 and 433

Upvotes: 0

Views: 772

Answers (3)

Nikhil Adiga
Nikhil Adiga

Reputation: 150

Install cors package using npm i cors

In your app.js file, const cors = require('cors')

app.use(cors());

Upvotes: 1

rajanbhadauria
rajanbhadauria

Reputation: 435

Danish try this solution, I hope it will work

const client = require("socket.io")(server, {
    handlePreflightRequest: (req, res) => {
        const headers = {
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
            "Access-Control-Allow-Origin": req.headers.origin, //or the specific origin you want to give access to,
            "Access-Control-Allow-Credentials": true
        };
        res.writeHead(200, headers);
        res.end();
    }
});

client.on("connection", () => {
    console.log("Connected!");
});

server.listen(443);

Upvotes: 1

rajanbhadauria
rajanbhadauria

Reputation: 435

// use CORS like that- // you need to use it as middle ware

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });

Upvotes: 1

Related Questions