CORS 被 node.js 和 socket.io 阻止
Posted
技术标签:
【中文标题】CORS 被 node.js 和 socket.io 阻止【英文标题】:CORS Blocked with node.js and socket.io 【发布时间】:2015-10-09 01:20:17 【问题描述】:我最近开始学习 node.js 和 socket.io。我遵循了 socket.io 的一个简单教程,并且在我的计算机上运行时一切正常。但是,我决定将客户端部分上传到服务器进行测试,这就是问题开始的地方。我想在网络主机上运行聊天客户端,并在我的计算机或其他主机上运行服务器。基本上,我计划端口转发服务器,并让客户端在网页上运行。我打开了我的端口以进行端口转发,它似乎正在工作,但是我每次都在网页上收到错误。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://24.151.51.34:3000/socket.io/?EIO=3&transport=polling&t=1437399007343-0. (Reason: CORS request failed).
我一直在搞乱代码,希望在开始我自己的项目之前找到解决这个问题的方法,但是我想不出办法。客户端代码是:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* margin: 0; padding: 0; box-sizing: border-box;
body font: 13px Helvetica, Arial;
form background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%;
form input border: 0; padding: 10px; width: 90%; margin-right: .5%;
form button width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px;
#messages list-style-type: none; margin: 0; padding: 0;
#messages li padding: 5px 10px;
#messages li:nth-child(odd) background: #eee;
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io('24.151.51.34:3000');
$('form').submit(function()
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
);
socket.on('chat message', function(msg)
$('#messages').append($('<li>').text(msg));
);
</script>
</body>
</html>
对于服务器代码,我尝试添加代码以允许 CORS,但真的不知道该怎么做:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.set('origins', 'http://browsercombat.com:80');
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");
res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
res.header("Access-Control-Allow-Credentials", "true");
next();
);
app.get('/', function(req, res, next)
res.sendFile(__dirname + '/index.html');
);
app.post('/', function(req, res, next)
// Handle the post for this route
);
io.on('connection', function(socket)
socket.on('chat message', function(msg)
io.emit('chat message', msg);
);
);
http.listen(3000, function()
console.log('listening on *:3000');
);
【问题讨论】:
myip
到底是什么?
啊,忘了说我是端口转发它连接到我的ip,我决定用“myip”替换它。
Express 和 socket.io 的 CORS 代码示例:enable-cors.org/server_expressjs.html 和 ***.com/questions/24058157/…。
您是否从“myip”地址提供客户端代码?
您是否尝试过添加更多选项,例如: res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");甚至更多: res.header("Access-Control-Allow-Credentials", "true");和 res.header("Access-Control-Max-Age", "....");
【参考方案1】:
除了使用 cors 包之外,我还设法通过在 socketio 创建中添加选项来修复它。从版本 3 开始,cors 配置已更改,您必须添加这些选项。 也适用于套接字版本 2.x.x。
const io = socketio(httpServer,
cors:
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true
);
这里是资源https://socket.io/docs/v3/handling-cors/
奖励:如果遇到错误请求,请确保客户端和服务器的 socket.io 版本相同。
【讨论】:
【参考方案2】:我设法通过使用有人推荐我的这个 CORS 中间件并检查我的防火墙设置来解决问题。 https://www.npmjs.com/package/cors
【讨论】:
【参考方案3】:我现在正在使用 npm cors 包,它就像一个魅力一样使用 socket.io 也没有问题。
像这样添加 app.options('*', cors());
这意味着 Access-Control-Allow-Origin: '*'
var express = require('express');
var app = express();
var http = require('http').Server(app);
const cors = require('cors');
var bodyParser = require('body-parser');
app.use(cors());
app.options('*', cors());
const auth = require('./routes/auth');
const port = 3004;
http.listen(port, () =>
console.log( `running http at port $port`);
);
【讨论】:
以上是关于CORS 被 node.js 和 socket.io 阻止的主要内容,如果未能解决你的问题,请参考以下文章
在使用 node.js 和 Express 构建的 api 中使用 cors 中间件时出现 CORS 错误
Post 请求 Node.js 和 React 的 CORS 错误
Angular.js 的 Node.js CORS 会话 cookie