基于this answer和this answer我能够嵌入我的页面内Grafana仪表板。
把你iframe
:
<iframe id="dashboard"></iframe>
,然后使用AJAX请求这样Grafana的内容给它:
<script type="text/javascript">
$.ajax(
{
type: 'GET',
url: 'http://localhost:3000/dashboard/db/your-dashboard-here',
contentType: 'application/json',
beforeSend: function(xhr, settings) {
xhr.setRequestHeader(
'Authorization', 'Basic ' + window.btoa('admin:admin')
);
},
success: function(data) {
$('#dashboard').attr('src', 'http://localhost:3000/dashboard/db/your-dashboard-here');
$('#dashboard').contents().find('html').html(data);
}
}
);
</script>
AJAX请求是必须的,因为它使您可以设置标题使用您的凭据。
在这一刻,您会因为CORS而从Grafana服务器获得空回复。你必须做的是为Grafana启用一些代理。有Grafana和使用nginx的泊坞窗容器的示例配置下面泊坞窗-组成:
version: '2.1'
services:
grafana:
image: grafana/grafana
nginx:
image: nginx
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
ports:
- 3000:80
你需要做的是提供您的nginx.conf文件的最后一件事:在提供
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,Authorization' 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;
}
}
}
此文件基础here,但重要的区别是
add_header 'Access-Control-Allow-Headers' 'Origin,Content-Type,Accept,Authorization' always;
这表示您允许设置Authorization
头。
你能在这方面取得进展吗? – creimers
我放弃了直接嵌入grafana图。相反,在我的应用程序中,我暴露了[Graphite API]的有趣部分(https://graphite-api.readthedocs.io/en/latest/)。他们以json的形式返回指标数据。在应用程序的管理面板中,我使用[chart.js](http://www.chartjs.org/)将图像渲染为图形。有点乏味,因为grafana已经使用相同的Graphite API做同样的事情,但是我发现没有办法在适当的限制下重用它。 – fracz
谢谢。希望能解决这个问题... – creimers