基於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