I'm currently learning how to create a chat app using Node and express for the backend and react for the frontend but am having a CORS error.
I'm getting this errror below because of CORS, however, I have implemented every CORS I can on the app.
This is the error
:3001/chat?name=jaden&room=love:1 Access to XMLHttpRequest at 'http://localhost:8000/socket.io/?EIO=4&transport=polling&t=NOYd8LK' from origin 'http://127.0.0.1:3001' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3001' that is not equal to the supplied origin.
polling-xhr.js:203 GET http://localhost:8000/socket.io/?EIO=4&transport=polling&t=NOYd8LK net::ERR_FAILED
create @ polling-xhr.js:203
Request @ polling-xhr.js:120
request @ polling-xhr.js:63
doPoll @ polling-xhr.js:92
poll @ polling.js:76
doOpen @ polling.js:23
open @ transport.js:43
open @ socket.js:170
Socket @ socket.js:94
push../node_modules/component-emitter/index.js.Emitter.emit @ index.js:145
onError @ polling-xhr.js:246
(anonymous) @ polling-xhr.js:196
setTimeout (async)
xhr.onreadystatechange @ polling-xhr.js:195
:3001/chat?name=jaden&room=love:1 Access to XMLHttpRequest at 'http://localhost:8000/socket.io/?EIO=4&transport=polling&t=NOYd9p5' from origin 'http://127.0.0.1:3001' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3001' that is not equal to the supplied origin.
polling-xhr.js:203 GET http://localhost:8000/socket.io/?EIO=4&transport=polling&t=NOYd9p5 net::ERR_FAILED
This is the backend Code
const express = require('express')
const http = require('http')
const socketIo = require('socket.io')
const cors = require('cors')
const app = express()
app.use(cors())
const server = http.createServer(app)
const io = socketIo(server, {
cors: {
origin: "http://localhost:3001",
methods: ["GET", "POST"]
}
})
// Listening for a connection on the socket.io server
io.on('connection', (socket)=>{
// the moment i get a connection, i want to send a welcome message
socket.on('join', ({name, room})=>{
socket.emit('message', {user:'admin', text:`${name}, You're welcome!`})
socket.broadcast.emit('message', {user:'admin', text:`${name}, just joined`})
console.log('welcome message')
})
socket.on('sendMessage', (message)=>{
io.emit('message', {user:'user', text:message})
})
socket.on("disconnect", ()=>{
io.emit('message', {user:'admin', text:`user Just left!`})
})
})
const port = process.env.PORT || 8000
server.listen(port, ()=> console.log(`Listening on port : ${port}`))