1
votes

When I am trying to connect using socketio client in the front end to the backened it is showin the error Access to XMLHttpRequest at 'http://localhost:8080/socket.io/?EIO=4&transport=polling&t=NOk7Aq9' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

front end code

import React, { Component, Fragment } from "react";

import openSocket from "socket.io-client";
import Post from "../../components/Feed/Post/Post";
import Button from "../../components/Button/Button";
import FeedEdit from "../../components/Feed/FeedEdit/FeedEdit";
import Input from "../../components/Form/Input/Input";
import Paginator from "../../components/Paginator/Paginator";
import Loader from "../../components/Loader/Loader";
import ErrorHandler from "../../components/ErrorHandler/ErrorHandler";
import "./Feed.css";

class Feed extends Component {
  state = {
    isEditing: false,
    posts: [],
    totalPosts: 0,
    editPost: null,
    status: "",
    postPage: 1,
    postsLoading: true,
    editLoading: false,
  };

  componentDidMount() {
    fetch("http://localhost:8080/feed/status", {
      headers: {
        Authorization: "Bearer " + this.props.token,
      },
    })
      .then((res) => {
        if (res.status !== 200) {
          throw new Error("Failed to fetch user status.");
        }
        return res.json();
      })
      .then((resData) => {
        console.log("status fetched ", resData.status);
        this.setState({ status: resData.status });
      })
      .catch(this.catchError);

    this.loadPosts();
    console.log("openSocket", openSocket);
    const socket = openSocket("http://localhost:8080/", {
      transports: ["polling", "websocket"],
      transportOptions: {
        polling: {
          extraHeaders: { "Access-Control-Allow-Origin": "*" },
        },
      },
    });
    socket.emit("connection", { data: "data" });
    socket.on("posts", (data) => {
      if (data.action === "create") {
        this.addPost(data.post);
      }
    });
  }





backend code 

mongoose
  .connect(
    "mongodb://chitesh:[email protected]:27017,cluster0-shard-00-01.ulx1q.mongodb.net:27017,cluster0-shard-00-02.ulx1q.mongodb.net:27017/feed?ssl=true&replicaSet=atlas-demxn2-shard-0&authSource=admin&retryWrites=true&w=majority",
    { useNewUrlParser: true, useUnifiedTopology: true }
  )
  .then((result) => {
    const server = app.listen(8080); // this basically return us the server
    const io = require("./socket.js").init(server);
    // websockets uses http protocols  the basis
    //so we are passing our http based server to the function
    // to create a websocket connection

    // we are setting up a function
    // to be executed whener a new connection is made

    io.on("connection", (socket) => {
      console.log("Client connected");
    });
  })
  .catch((error) => {
    console.log(error);
  });


socket.js 

const { listenerCount } = require("./models/post");

let io;
module.exports = {
  init: (httpServer) => {
    io = require("socket.io")(httpServer);
    return io;
  },
  getIO: () => {
    if (!io) {
      let error = new Error("Socket.io is not initialized");
      throw error;
    }`enter code here`
    return io;
  },
};
1

1 Answers

0
votes

Take a look at express CORS middleware. You'll need to allow localhost:3000 to be used as origin.

You can use something like

var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
origin: 'http://localhost:3000',
}

app.use(cors(corsOptions))