I am trying to develop a simple chat app using Node, React, Express & Socket.io.
Here is my Node server set up:
const express = require("express");
const cors = require('cors');
const http = require('http');
const socketio = require('socket.io');
// ENV VARS
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
const SERVER_PORT = process.env.SERVER_PORT || 5000;
const HOST = process.env.HOST || "http://localhost";
// INIT
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// MIDDLEWARE
app.use(cors());
app.use(express.urlencoded({extended: false}));
app.use(express.json());
io.on('connection', (socket) => {
console.log('new client connected');
});
// ON LISTEN
server.listen(SERVER_PORT, () => {
console.log(`app listening at ${HOST}:${SERVER_PORT}`);
});
Here is my client side:
import {io} from "socket.io-client";
import './App.css';
const PORT = 5000
const HOST = "http://localhost"
const SERVER_URL = HOST + ':' + PORT
console.log(SERVER_URL);
function App() {
let socket = io(SERVER_URL);
return (
<div className="App">
aaaa
</div>
);
}
export default App;
I simply tried to test the on connection event, Yet I am getting the following error:
Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NbN5Yrt' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
polling-xhr.js:203 GET http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NbN5Yrt net::ERR_FAILED
i tried adding:
{origins: '*'}
as socket io doc says but the errors are still showing. What am I doing wrong?
npm startyou're starting a development server by default atlocalhost:3000. I think I should pre-emptively tell you when you build the production version of your app in the future usingnpm run buildyou'll need to serve those files somehow as you won't be able to use the dev server then. - Danoram