Skip to content Skip to sidebar Skip to footer

Cors Validation For Web Socket

I'm using expressjs and added cors validation for a all origins. const options = { origin: ['*'], credentials: true, exposedHeaders: false, preflightContinue: false, opt

Solution 1:

my example that is working, socket are to different server

// socket.js server config,for expressconst app = express();
const server = app.listen(process.env.SOCKET_PORT, function () {
    console.log("Server started: http://localhost:" + process.env.SOCKET_PORT + "/");
});

app.use(function (req, res, next) {
    res.setHeader(
        "Access-Control-Allow-Headers",
        "X-Access-Token, Content-Type, Lang, crossDomain"
    );
    res.setHeader(
        "Access-Control-Allow-Methods",
        "POST, GET, OPTIONS, PUT, DELETE"
    );
    res.setHeader("Access-Control-Allow-Origin", "*");
    req.headers.host = req.headers["x-forwarded-host"];
    res.setHeader("Cache-Control", "no-cache");

    //intercepts OPTIONS methodif ('OPTIONS' === req.method) {
        //respond with 200
        res.sendStatus(200);
    } else {
        //move onnext();
    }
});

const io = require('socket.io')(server, {
    transports: [
        // 'polling',"websocket"
    ],
    allowUpgrades: true,
    adapter: redisAdapter({host: 'localhost', port: process.env.REDIS_PORT || '6379'}),
    pingInterval: 3000,
    wsEngine: 'ws'
})

also I have config inside nginx.conf

 location / {
// important line

        proxy_set_header 'Access-Control-Allow-Origin''*';
        proxy_set_header 'Access-Control-Allow-Methods''GET, POST, OPTIONS';

  # redirect all traffic to local port;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For$proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_redirect off;
        proxy_read_timeout 86400;

        # prevents 502 bad gateway error
        proxy_buffers 832k;
        proxy_buffer_size 64k;

        reset_timedout_connection on;


//your port here
        proxy_pass http://localhost:YOUR_PORT;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }


Solution 2:

adding cors:true to the options object worked for me

constoptions= {
origin: ['*'],
cors:true,
credentials:true,
exposedHeaders:false,
preflightContinue:false,
optionsSuccessStatus:204,
methods: ['GET', 'POST'],
allowedHeaders:allowedHeaders,
};

Post a Comment for "Cors Validation For Web Socket"