我继续收到
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); }); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。