"Origin null is not allowed by Access-Control-Allow-Origin" 错误
发布于 12 年前 作者 jiyinyiyong 27561 次浏览 最后一次编辑是 8 年前

想试试看弄个能本地编辑网页然后连接 socket.io 的服务器, 遇到这个问题…
我把服务器运行在 8000 端口, 然后浏览器上这样方访问:

window.socket = io.connect('127.0.0.1:8000');

但是为了跨域名的脚本能连接上, 对 socket.io 添加设置…
http://stackoverflow.com/questions/6736706/socket-io-access-control-allow-origin-error-from-remote-site

var socket  = io.listen(app,{origins: '*:*'});

结果 Chrome 上还是遇到了这个报错,

Origin null is not allowed by Access-Control-Allow-Origin.

搜索结果大概说不同浏览器对这个安全问题的处理不同, Firefox 就可以的.
还有就是把文件放在一个服务器上, 就可以正常连接了.
后边搜到有两个解决的方案, 一个还是放到服务器上,
另一个是在启动 Chrome 时使用选项 --allow-file-access-from-files
具体看这个 issue https://github.com/LearnBoost/socket.io/issues/801


还一个 Chrome 的 console.log.apply 有个 illegal invocation, 办法在这:
http://stackoverflow.com/questions/8159233/typeerror-illegal-invocation-on-console-log-apply


后来用 socket.io 所运行服务器端口以外的方法连接 socket 遇到下面错误,
而且我已经家参数启动和设置 origins 参数的情况下:

Origin file:// is not allowed by Access-Control-Allow-Origin.  

http://stackoverflow.com/questions/9833641/error-in-chrome-origin-file-is-not-allowed-by-access-control-allow-origin
还没找到办法… Chrome 18 …

5 回复

加了–allow-file-access-from-files还是没用

No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘file://’ is therefore not allowed access.

跨域问题, 通过服务端处理 CORS 来搞定… 我后来遇到的情况比较复杂的情况下的一篇笔记: http://blog.segmentfault.com/jiyinyiyong/1190000000503451 简单的方案是安装用 cors 模块在返回的请求头上写允许 CORS 的声明代码

@jiyinyiyong 不使用XMLHttpRequest对象,是否就可以绕过not allowed by Access-Control-Allow-Origin问题呢?

@fenode 不用这个 API 怎么访问网络啊… 除了 IE 我没看到还有能替代的 API 可以用

回到顶部