node.js - How to enable CORS on express.js 4.x on all files? -
i keep receiving
cross-origin request blocked: same origin policy disallows reading remote resource @ http://example.com:2013/socket.io/?eio=3&transport=polling&t=1433950808025-0. (reason: cors request failed).
while try access node.js. doesn't work 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 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);
try solution (edited 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); }); });
Comments
Post a Comment