我继续收到
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
07000.
(Reason: CORS request Failed).
而我尝试访问我的node.js.这对我来说不行:
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:这是更新完整的代码:
var express = require('express'); var http = require('http'); var expressvar = express(); expressvar.use(function (req,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);
解决方法
尝试这个解决方案(编辑包括完整的工作代码)
var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); io.set('origins','*:*'); app.use(function(req,next) { res.header('Access-Control-Allow-Origin',req.get('Origin') || '*'); res.header('Access-Control-Allow-Credentials','true'); res.header('Access-Control-Allow-Methods',DELETE'); res.header('Access-Control-Expose-Headers','Content-Length'); res.header('Access-Control-Allow-Headers','Accept,Authorization,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); }); });