[英]Socket.io with local client. Origin null and Access-Control-Allow-Origin
I'm trying to test a simple socket.io example with a local client. 我正在尝试使用本地客户端测试一个简单的socket.io示例。 Here is my code: 这是我的代码:
server: 服务器:
var sio = require('socket.io');
var io = sio.listen(8077, {log: false});
io.sockets.on('connection', function (socket) {
console.log('connection detected');
socket.on('hello', function(data){
console.log('hello received: ' + data);
});
});
client: 客户:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="socket.io-client/dist/socket.io.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
var socket = io.connect('http://localhost:8077');
if(socket != undefined){
socket.emit('hello', 'this is a test');
}
</script>
</body>
</html>
If I put my client in a remote server, it runs perfectly, but if I try to run my client from local, my browser gives me the following error: 如果我将我的客户端放在远程服务器上,它运行完美,但如果我尝试从本地运行我的客户端,我的浏览器会给我以下错误:
XMLHttpRequest cannot load http://localhost:8077/socket.io/1/?t=1343494806858.
Origin null is not allowed by Access-Control-Allow-Origin
I know that there is a http header which solves this problem in a http server, but I don't know if there is a similar option in sockets context. 我知道有一个http头在http服务器中解决了这个问题,但我不知道在套接字上下文中是否有类似的选项。 I need a local client. 我需要一个本地客户。 I don't want to serve the client code from an extra http nodejs server. 我不想从额外的http nodejs服务器提供客户端代码。
Have you tried setting the server origins parameter (it sets the header you mentioned)?: 您是否尝试过设置server origin参数(它设置了您提到的标题)?:
var sio = require('socket.io');
var io = sio.listen(8077, {log: false, origins: '*:*'});
Also now your not accessing that server locally, have you made sure to update the line: 此外,您现在无法在本地访问该服务器,请确保更新该行:
var socket = io.connect('http://localhost:8077');
to include the ip (or domain if you have one) of the remote server: 包括远程服务器的ip(或域名,如果有的话):
var socket = io.connect('http://XX.XX.XX.XX:8077');
Can you see what line returns the error in the console (you using chrome/ff with firebug?). 你能看到哪一行在控制台中返回错误(你使用chrome / ff和firebug吗?)。 In the if statement the socket variable will probably never by undefined. 在if语句中,socket变量可能永远不会是未定义的。 The the recommended way to use the connection is to wait for it to be ready by attaching a callback to the connect event, eg: 使用连接的推荐方法是通过将回调附加到connect事件来等待它准备就绪,例如:
socket.on('connect', function () { // <-instead of the if
socket.emit('hello', 'this is a test');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.