EDIT 2:
As for why you're getting that CORS error, it's because you haven't configured the Socket.IO cors
option properly.
Now, the cors
configuration for Socket.IO actually gets passed to the NPM package cors
, so you need to make your cors
configuration work with the cors
package.
For your case, that would look like:
cors: {
// The `*` is used as the wildcard here.
origin: "*",
// Set the other options according to your needs.
// The docs are here:
// https://www.npmjs.com/package/cors#configuration-options
methods: ["GET", "POST"],
allowedHeaders: ["content-type"]
}
EDIT 1:
Now that I know you are using Socket.IO 3.0, I may be able to help you better.
Socket.IO 3.0 includes a bunch of breaking changes (see the full changelog here), so that may be why you are getting that TypeError: io.origins is not a function
.
As for that CORS error, Socket.IO 3.0 removed some old options, and added some new ones for CORS management. One of the removed options was the origins
property. That's why your code is not working: you aren't actually setting any CORS configurations. To set CORS configurations in Socket.IO 3.0, use the options below:
// I still use a port here, because it works, but you could use @Aryas'
// code if you wish.
const io = socketIO(3000, {
// Now, the CORS config.
// You could either use the new `cors` property...
cors: {
origin: "https://example.com",
methods: ["GET", "POST"],
allowedHeaders: ["content-type"]
},
// ...Or the old `allowRequest` function.
allowRequest: function(req, callback) {
callback(null, req.headers.referer.startsWith("https://example.com"));
}
});
Oh, and, setting CORS options in Express is not necessary; Socket.IO picks up requests that are for it automatically, before any Express handlers are called.
ORIGINAL ANSWER:
It's telling you that because your io
variable is not an instance of the Socket.IO server. Instead, it's the Socket.IO server constructor. Why?
Well, you have this code:
// You are passing two parameters to `require`: "socket.io", and 3000
var io = require("socket.io", 3000);
require
returns whatever is exported by the module, which, in this case, is the Socket.IO server constructor (not an instance of it). The 3000
you passed to require
doesn't do anything, since require
only accepts one argument.
In order to get a Socket.IO server instance, you need to do this:
// The clearer way:
// `socketIO` is the Socket.IO server constructor.
var socketIO = require("socket.io");
// `io` is the Socket.IO server instance.
var io = socketIO(3000);
// The shorter way:
// Calling the result of `require` (the Socket.IO server constructor) as a function.
var io = require("socket.io")(3000);