跨域请求被阻止 Elasticsearch

9

你好,我正在运行 Elasticsearch 2.3 版本,并且有一段 Angular 代码用于查询搜索。当我运行它时,即使将 http.cors.enabled 设置为 true,http.cors.allow-origin 设置为 /https?:\/\/localhost(:[0-9]+)?/,我仍然遇到了这个错误。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:9200/elastic/_search?size=50. This can be fixed by moving the resource to the same domain or enabling CORS

我不明白问题出在哪里。
我的请求头。
    User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0
Pragma: no-cache
Origin: http://127.0.0.1:8100
Host:   localhost:9200
Connection: keep-alive
Cache-Control:  no-cache
Access-Control-Request-Method:  POST
Access-Control-Request-Headers: content-type
Accept-Language:    en-US,en;q=0.5
Accept-Encoding:    gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

我的控制台看起来像这样。输入图像描述但是,如果我直接在浏览器中输入请求,就会得到正确的输出。输入图像描述

你是通过 file:/// 协议加载页面还是在本地主机上由 Web 服务器提供服务?类似的问题可以在这里找到:http://stackoverflow.com/questions/36907355/elasticsearch-cross-origin-request-blocked-despite-configuring-http-module/36907386#36907386 - Val
1
通过 file://... 这样做有什么区别吗? - NEz
1
我尝试通过安装一个简单的HTTP服务器来运行,但仍然存在同样的问题,而且我正在运行Elasticsearch 2.3.3。 - NEz
你能否更新你的问题,包括HTTP请求和响应中的请求头? - Val
我相信有很多这样的问题在飞来飞去,可能值得在Elasticsearch和CORS上进行广泛搜索。 - Callum Linington
显示剩余6条评论
4个回答

28

我通过添加这些行到我的yml文件中并重新启动ES来解决了这个问题。

 http.cors.enabled : true
 http.cors.allow-origin: "*"
 http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
 http.cors.allow-headers: X-Requested-With,X-Auth-Token,Content-Type,Content-Length
 http.cors.allow-credentials: true

3
测试:curl --head http://localhost:9200 -H 'Origin: http://example.com' 请注意,此命令需要在终端或命令行界面中运行。该命令用于从本地主机(即您的计算机)向URL http://localhost:9200 发送HTTP请求,并使用标头 "Origin: http://example.com"。 - Oshan Wisumperuma
它对我有效,但我有一个疑问,为什么当我从C#代码访问相同的数据时没有出现错误? - Techie Boy
@TechieBoy 因为CORS只是浏览器中的一种安全机制,它并不影响服务器端的代码。 - bfontaine

1

这里有一个弹性云的示例,如果有人需要的话。

https://docs.elastic.co/search-ui/tutorials/elasticsearch

http.cors.allow-origin: "*"
http.cors.enabled: true
http.cors.allow-credentials: true
http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
http.cors.allow-headers: X-Requested-With, X-Auth-Token, Content-Type, Content-Length, Authorization, Access-Control-Allow-Headers, Accept, x-elastic-client-meta

0
如果您不想修改elasticsearch.yml文件,您可以使用这个Chrome扩展程序来禁用CORS。

4
这只适用于调试,不可行的解决方案是要求所有用户安装Chrome扩展程序来禁用CORS。 - Botond Kopacz
@Mahdi:Chrome扩展链接已经失效了。如果可能的话,你能否更新一下它? - shivshankar

-2

为了开发目的,可以像 @Mahdi 指出的那样使用 Chrome 扩展程序 Allow CORS: Access-Control-Allow-Origin。该扩展程序会将 (Access-Control-Allow-Origin: *) 规则添加到响应头中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接