I am getting following error:
Access to XMLHttpRequest at ‘http://localhost:8001/socket.io/?EIO=3&transport=polling&t=NWrnTy1’ from origin ‘http://localhost’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
my node server code:
//import express from "express";
//import http from "http";
const app = require("express")();
const server = require("http").createServer(app);
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
const io = require("socket.io")(server);
io.on("connection", () => {
console.log("Connected!");
});
var redis = require('redis');
var url = "redis://localhost:6379"
var client = redis.createClient(url);
client.on('message', function(channel, msg) {
io.sockets.emit(msg);
});
client.subscribe('JoinCall');
server.listen(8001);
my index.html on apache:
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
//var socket = io();
var socket = io.connect('http://localhost:8001');
sock.on('twits', function(msg) {
console.log('message received: '+msg);//Do something with message here.
});
</script>
2
Answers
in socket.io client I used a neutral transport layer:
I had ton of problems with CORS and they were all resolved by installing the npm package cors and let it do this job. I would suggest to remove your manual setting headers and try this instead. Saved my life.
Install the cors package by running ‘npm i cors’. Then in your server file add these: