跨域事件源
我正在尝试使用nodejs 创建一个EventSource 服务器,它将服务器跨域请求。我正在发回 Access-Control-Allow-Origin 标头,但浏览器(Chrome 或 Opera 也不是)不允许我连接。我发回了一些标头:
this._response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true'
});
我怎样才能正确地做到这一点?
问候
I am trying to create an EventSource server using nodejs, that will server requests cross domain. I am sending back Access-Control-Allow-Origin header, but the browser (nor Chrome or Opera) won`t let me connect. There are the headers I send back:
this._response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true'
});
How can I do this the right way?
Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Allow-Credentials
不能与Allow-Origin
设置为*
一起使用。考虑在您的响应中写入收到的 Origin-header。
Allow-Credentials
cannot be used withAllow-Origin
set to*
.Consider writing the received Origin-header in your response.
参见 https://github.com/Yaffle/EventSource - 可以采用polyfill来支持Firefox的CORS, Webkit 和 IE 8+
see https://github.com/Yaffle/EventSource - polyfill can be adopted to support CORS for Firefox, Webkit and IE 8+
尝试使用以下块代替您的块。浏览器将使用
OPTIONS
调用一次,然后将按预期发出请求。如果您已经分解了请求方法,则不需要
if
语句 - 但我想给您一个完整的块,以防万一您像 Hello World 例子就是这样。Try the following block in place of yours. The browser will call one time with
OPTIONS
and then the request will be made as expected after that.You won't need the
if
statement if you have broken out the request methods - but I wanted to give you a full block just in case you're hosting it like the Hello World example did.如果您使用跨域资源,您会收到
安全异常(SECURITY_ERR:DOM 异常18)
。这可能是由于:file://
访问本地资源(本地文件不通过节点服务器提供)或You get
Security Exception (SECURITY_ERR: DOM Exception 18)
if you are using cross domain resources. This could be due to :file://
(local files not served via node server) orhttps://developer.mozilla.org/en-US/ docs/Web/HTTP/CORS#simple_requests
所以:(
服务器端)
如果客户端的
来源
(req.headers.origin
) 是受信任的。或者只需设置
{withCredentials: false}
(客户端)并使用res.setHeader( 'Access-Control-Allow-Origin', '*')
如果您不需要它。https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests
So:
(server-side)
if client's
origin
(req.headers.origin
) is trusted.Or simply set
{withCredentials: false}
(client-side) and useres.setHeader('Access-Control-Allow-Origin', '*')
if you don't need it.