I keep receiving
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com:2013/socket.io/?EIO=3&transport=polling&t=1433950808025-0. (Reason: CORS request failed).
while I try to access my node.js. This doesn't work for me:
app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });
@edit: here is the updated full code:
var express = require('express'); var http = require('http'); var expressvar = express(); expressvar.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Headers', 'accept, authorization, content-type, x-requested-with'); res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE'); res.setHeader('Access-Control-Allow-Origin', req.header('origin')); next(); }); expressvar.use(express.static('../')); expressvar.use("/socket.io", express.static('../socket.io')); var app = http.createServer(expressvar); var io = require('socket.io').listen(app); app.listen(2013);
1 Answer. Show activity on this post. Install cors library npm install cors --save and use it like so. I already bye-pass cors with request library.
To solve this error, we need to add the CORS header to the server and give https://www.section.io access to the server response. Include the following in your index. js file. const cors = require('cors'); app.
Try this solution (edited to include full working code)
var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); io.set('origins', '*:*'); app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', req.get('Origin') || '*'); res.header('Access-Control-Allow-Credentials', 'true'); res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE'); res.header('Access-Control-Expose-Headers', 'Content-Length'); res.header('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type, X-Requested-With, Range'); if (req.method === 'OPTIONS') { return res.send(200); } else { return next(); } }); server.listen(80); app.get('/', function (req, res) { res.send('OK'); }); io.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); });
cors package does this
// npm install --save cors var express = require('express'); var cors = require('cors'); var app = express(); app.use(cors()); app.use(express.static()); app.get('*', function(){}); require('http').createServer(app).listen(3000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With