简体   繁体   中英

No 'Access-Control-Allow-Origin' - Node / react / socket.io

I have try to use socket.io in my project to do real-time notifications, but I got a console error, here's my example backend ( nodejs ):

const express = require('express');
const app = express();
const Server = app.listen(1337);

const io = require('socket.io')(Server, {
    origins: ["http://localhost:3000"],
    handlePreflightRequest: (req, res) => {
        res.writeHead(200, {
          "Access-Control-Allow-Origin": "http://localhost:3000",
          "Access-Control-Allow-Methods": "GET,POST",
          "Access-Control-Allow-Headers": "my-custom-header",
          "Access-Control-Allow-Credentials": true
        });
        res.end();
    }
});

io.on('connection', (socket) => {
    console.log('connected');
    socket.on('message', (message) => {
        console.log('message');
    })
    socket.emit('message', 'toto');
});

frontend (Reactjs):

import './App.css';
import React, {useState, useEffect} from 'react';
import io from 'socket.io-client'

const socket = io('http://localhost:1337',{
  withCredentials: true
})

function App() {
  return (
    <div className="App">
    {/* <script src="http://localhost:1337/socket.io/socket.io.js"></script> */}
    </div>
  );
}

export default App;

and here's the error is shown on my navigator console:

Access to XMLHttpRequest at 'http://localhost:1337/socket.io/?EIO=4&transport=polling&t=NVYt_fH' 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.
polling-xhr.js:202 GET http://localhost:1337/socket.io/?EIO=4&transport=polling&t=NVYuaDS net::ERR_FAILED

I can't figure out my error, I have tried with too many solutions but no thing was helping/

Thank you @Beerswiller for your interest, I found what I miss is:

instead of using:

const io = require('socket.io')(Server, {
    origins: ["http://localhost:3000"],
    handlePreflightRequest: (req, res) => {
        res.writeHead(200, {
          "Access-Control-Allow-Origin": "http://localhost:3000",
          "Access-Control-Allow-Methods": "GET,POST",
          "Access-Control-Allow-Headers": "my-custom-header",
          "Access-Control-Allow-Credentials": true
        });
        res.end();
    }
});

i changed to:

const io = require('socket.io')(Server, {
    cors: {
        origin : "http://localhost:3000"
    }
});

and on the front section i do:

const socket = io('http://localhost:1337')

instead of:

const socket = io('http://localhost:1337',{
  withCredentials: true
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM