Using require('cors') but still getting CORS error

Viewed 411

I'm trying to build a simple React/Node/Socket.io app.

Here's the React app.js:

import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://127.0.0.1:4001";

function App() {
  const [response, setResponse] = useState("");

  useEffect(() => {
    const socket = socketIOClient(ENDPOINT);
    socket.on("FromAPI", data => {
      setResponse(data);
    });
  }, []);

  return (
    <p>
      It's <time dateTime={response}>{response}</time>
    </p>
  );
}

export default App;

And here's the Node app.js:

const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const cors = require('cors');

const port = process.env.PORT || 4001;
const index = require("./routes/index");

const app = express();
//app.use(cors());
app.use(cors({
    origin: ['http://localhost:3000'],
    credentials: true
}));
app.use(index);

const server = http.createServer(app);
const io = socketIo(server);

let interval;

io.on("connection", (socket) => {
  console.log("New client connected");
  if (interval) {
    clearInterval(interval);
  }
  interval = setInterval(() => getApiAndEmit(socket), 1000);
  socket.on("disconnect", () => {
    console.log("Client disconnected");
    clearInterval(interval);
  });
});

const getApiAndEmit = socket => {
  const response = new Date();
  // Emitting a new message. Will be consumed by the client
  socket.emit("FromAPI", response);
};

server.listen(port, () => console.log(`Listening on port ${port}`));

When I load localhost:3000 and check the JavaScript console, I get this error:

GET http://127.0.0.1:4001/socket.io/?EIO=4&transport=polling&t=NgNHj7X net::ERR_FAILED
Access to XMLHttpRequest at 'http://127.0.0.1:4001/socket.io/?EIO=4&transport=polling&t=NgNHkML' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Shouldn't the require('cors') and app.use(cors()) be resolving this? I tried with both

app.use(cors())

and

app.use(cors({
        origin: ['http://localhost:3000'],
        credentials: true
    }));

but got the same result regardless.

EDIT: per the Socket.io documentation here, I tried this:

const socketIo = require("socket.io",{
    cors: {
      origin: "http://localhost:3000",
      methods: ["GET", "POST"]
    }
  });

but that gave the same error.

2 Answers

Passing the CORS parameters into the socketIO constructor resolved the issue, as follows:

const io = socketIo(server,{
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"],
    credentials:true
  }
});

Double check at your allowedHeaders and allowed methods, working example:

const corsOptions = {
    allowedHeaders: ['X-ACCESS_TOKEN', 'Access-Control-Allow-Origin', 'Authorization', 'Origin', 'x-requested-with', 'Content-Type', 'Content-Range', 'Content-Disposition', 'Content-Description'],
    credentials: true,
    methods: 'GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE',
    origin: ['http://macog.local:5001','http://localhost:5001', 'https://app.foo.com', 'http://10.0.2.2:5001'],
    preflightContinue: false
};
Related