Socket.io + Node.js跨源请求被阻止 [英] Socket.io + Node.js Cross-Origin Request Blocked

查看:965
本文介绍了Socket.io + Node.js跨源请求被阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用node和socket.io来编写聊天应用程序。它在Chrome上正常工作,但mozilla发出错误,以启用跨源请求。

I'm using node and socket.io to write a chat application. It works fine on Chrome but mozilla gives an error to enable the Cross-Origin Requests.


跨原始请求被阻止:不允许读取 http ://waleedahmad.kd.io:3000 / socket.io /?EIO = 2& transport = polling& t = 1401964309289-2& sid = 10yDavRDf4WErI-VAAAI 。这可以通过将资源移动到相同的域或启用CORS来修复。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://waleedahmad.kd.io:3000/socket.io/?EIO=2&transport=polling&t=1401964309289-2&sid=1OyDavRDf4WErI-VAAAI. This can be fixed by moving the resource to the same domain or enabling CORS.

这是我的代码启动节点服务器。 >

Here's my code to start node server.

var express = require('express'),
    app = express(), 
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    path = require('path');
server.listen(3000);

app.get('/', function(req, res) {
    res.sendfile(__dirname + '/public/index.html');
});

在客户端。

var socket = io.connect('//waleedahmad.kd.io:3000/');

HTML页面上的脚本标记。

Script tag on HTML page.

<script type="text/javascript" src="//waleedahmad.kd.io:3000/socket.io/socket.io.js"></script>

我也在应用程序根目录下使用.htaccess文件。 (waleedahmad.kd.io/node)。

I'm also using .htaccess file in the app root directory. (waleedahmad.kd.io/node).

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"


推荐答案

您可以尝试设置 c $ c>选项在服务器端允许跨源请求:

You can try to set origins option on the server side to allow cross-origin requests:

io.set('origins', 'http://yourdomain.com:80');

这里 http://yourdomain.com:80 是您要允许请求的来源。

Here http://yourdomain.com:80 is the origin you want to allow requests from.

您可以阅读更多关于 origins =http://stackoverflow.com/a/21711242/2600208>这里

You can read more about origins format here

这篇关于Socket.io + Node.js跨源请求被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆