我将Grafana设置在Docker容器(来自Docker repo的grafana/grafana
映像)中,并将端口3000转发到我的localhost。我的docker-compose.yml
如下:
version: '2.1'
services:
grafana:
image: grafana/grafana
ports:
- 3000:3000
最初我也有Graphite和一些卷和环境配置的链接(仅GF_SECURITY_ADMIN_PASSWORD
),但我认为没关系。
我可以通过简单的curl
电话获得Grafana的回复:
$ curl http://localhost:3000
<a href="/login">Found</a>.
但是当我试图通过AJAX调用来获取它时,它给了我一个奇怪的结果:
$.ajax({url: 'http://localhost:3000', beforeSend: function(xhr, settings) {alert('before setting header'); xhr.setRequestHeader('Access-Control-Allow-Origin', '*'); alert('after setting header');}});
[many JSON fields]
responseText:""
[many JSON fields]
statusText: "error"
[many JSON fields]
警报表示标头设置为接受来自任何来源的请求。
当我直接调用Docker容器地址时,同样的情况发生(curl工作,但ajax没有)。
后台会发生什么?为什么第二个请求不起作用?如何通过AJAX电话获得Grafana的回复?
答案 0 :(得分:3)
问题是默认情况下,在grafana上未启用CORS。 curl请求不会检查CORS,但浏览器会检查CORS。这是保护一个站点调用其他站点的API的原因。
所以你的解决方案是在Grafana面前放一个反向nginx代理。以下是相同
的docker-compose.yml
version: '2.1'
services:
grafana:
image: grafana/grafana
nginx:
image: nginx
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
ports:
- "3000:80"
在nginx配置下面会添加CORS,但它非常开放会让每个人都能访问
events {
worker_connections 1024;
}
http {
#
# Acts as a nginx HTTPS proxy server
# enabling CORS only to domains matched by regex
# /https?://.*\.mckinsey\.com(:[0-9]+)?)/
#
# Based on:
# * http://blog.themillhousegroup.com/2013/05/nginx-as-cors-enabled-https-proxy.html
# * http://enable-cors.org/server_nginx.html
#
server {
listen 80;
location / {
#if ($http_origin ~* (https?://.*\.tarunlalwani\.com(:[0-9]+)?$)) {
# set $cors "1";
#}
set $cors "1";
# OPTIONS indicates a CORS pre-flight request
if ($request_method = 'OPTIONS') {
set $cors "${cors}o";
}
# Append CORS headers to any request from
# allowed CORS domain, except OPTIONS
if ($cors = "1") {
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Credentials true always;
proxy_pass http://grafana:3000;
}
# OPTIONS (pre-flight) request from allowed
# CORS domain. return response directly
if ($cors = "1o") {
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Headers' 'Origin,Content-Type,Accept' always;
add_header Content-Length 0;
add_header Content-Type text/plain;
return 204;
}
# Requests from non-allowed CORS domains
proxy_pass http://grafana:3000;
}
}
}
另外,对于测试,你不应该使用
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
删除并测试它应该可以正常工作