I have two different machines connect to same network.
I wanted to connect over LAN Network using LAN assigned IP address below is the simple demonstration
Socket Client (Reactjs, IP : 192.168.0.103) to Socket Server (Express, IP :192.168.0.114)
Problem : Getting error : Access blocked by CORS (tried express 'cors' middleware but failed with no solution)
Here is Simple React Code which is working fine
import socketClient from 'socket.io-client';
const SocketServer = 'http://192.168.0.114:3000';
function App() {
var socket = socketClient(SocketServer, {secure: true});
socket.emit('client_connected', { payload: {
message: "react client is connected"
}});
return (
<div>
</div>
);
}
export default App;
And simple express code (which also working fine)
const cors = require('cors')
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const http = require('http')
const server = http.createServer(app)
const { Server } = require('socket.io')
const io = new Server(server)
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.static('public'))
app.use(cors({
origin: '*'
}));
app.set('view engine', 'ejs')
app.get('/', (req,res) => {
res.sendFile(__dirname '/index.html')
})
io.on('connection', (socket) => {
socket.on('client_connected', (message) => {
console.log(message)
})
})
server.listen(3000, () => {
console.log('listening on *:3000');
});
Error screenshot getting in Browser console on ReatJs
I tried setting up headers in express but getting same error
Any help will be appreciated
CodePudding user response:
You need to configure cors in the socket server not express
take a look here to know more about the configuration https://socket.io/docs/v3/handling-cors/
configuration example
const io = require("socket.io")(httpServer, {
cors: {
origin: "https://example.com",
methods: ["GET", "POST"]
}
});