Getting CORS error when using socket.io/nginx/node
I am getting this error log from Chrome console
XMLHttpRequest cannot load https://subgroup.domain.com/socket.io/?EIO=3&transport=polling&t=Lpgp_mu . The requested resource does not have an "Access-Control-Allow-Origin" header. Origin ' http: // localhost: 3000 ' is therefore not allowed. The response was HTTP status code 500.
I am using Node.js, socket.io for conversation between my node and react.js, with a digitalocean blob using nginx to host them.
I've read a lot about CORS errors and I'm not sure where to fix the error. I tried to resolve them in my NGINX
location /server {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Access-Control-Allow-Origin *;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
And with my Node.js, on the server side:
var express = require("express");
var app = express();
var http = require("http");
var port = 8080;
var io = require("socket.io").listen(app.listen(port));
app.use("/", function (req, res, next) {
res.status(200).send("Online |" + " Version : [" + AppVersion + "]");
res.setHeader("Access-Control-Allow-Origin","*");
res.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type");
res.setHeader("Access-Control-Allow-Methods","GET,POST, OPTIONS, PUT, PATCH, DELETE");
next();});
And I am connecting on the client side using:
const socket = io.connect("https://subgroup.domain.com/server")
I'm not sure where or what I should be looking for. Any help would help. Thank!
source to share
After a lot of research and doing a few tests, I got this job. Here's what I did,
NodeJS
const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('A user connected!');
io.emit('welcome', 'Hello there!');
});
server.listen(3001);
console.log('Socket server started on port 3001');
Nginx
upstream websocket1 {
server 127.0.0.1:3001;
}
server {
listen 80;
listen [::]:80;
root /var/www/html;
server_name mydomain.com
location /ws/ {
proxy_pass http://websocket1/socket.io/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
Finally, on the client side
const socket = io.connect('http://yourdomain.com/', {path: '/ws/'})
Here is a screenshot from the Chrome console.
Please don't ignore /
after specifying location
in Nginx, it should be /ws/
, otherwise it won't work. I currently have a node balancer added to this socket service using Nginx.
Hooray!
source to share