I'm trying to connect a client to a server socket and I'm getting this error.
Access to fetch at 'http://localhost:9999/socket.io/?EIO=4&transport=polling&t=NTQGzyP&b64=1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I've looked at answers to similar questions and tried them with no change. This includes setting the headers using WebApp.rawConnectHandlers
and setting the cors options to no avail. I've spent a lot of time copying the different solutions others have mentioned but it doesn't seem to make a difference.
I've tried adding the headers before and after creating the server.
Client
const io = require("socket.io-client")
const socket = io.connect("http://localhost:9999/")
Server
import {Meteor} from 'meteor/meteor';
import http, * as Http from 'http';
import {Socket} from 'socket.io';
import {WebApp} from "meteor/webapp";
Meteor.startup(() => {
// Server
const server: Http.Server = http.createServer();
WebApp.rawConnectHandlers.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
return next();
});
const io = require('socket.io')(server);
io.on('connection', (socket: Socket)=>{
socket.on('hello',(data)=>{
console.log('HELLO BISH')
console.log(data.text)
})
})
// Start server
try {
server.listen(9999);
} catch (e) {
console.error(e);
}
});
What is the correct method of allowing the connection?
To fix this I had to set the cors configuration for the socket. I allowed http://localhost:3000
to connect to it which now allows my webpage to communicate with the socket server.
const io = require("socket.io")(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
});