fix: proxy device metrics through backend to avoid CORS

This commit is contained in:
tian 2026-05-08 19:41:42 +08:00
parent 0d55213101
commit 0dede50f9e
2 changed files with 14 additions and 2 deletions

View File

@ -677,6 +677,7 @@ func (u *UI) Routes() (chi.Router, error) {
r.Get("/monitor", u.pageMonitor)
r.Get("/hls/*", u.proxyHLS)
r.Get("/api/monitor/channels", u.apiMonitorChannels)
r.Get("/api/device-metrics", u.apiDeviceMetrics)
r.Get("/recognition", u.pageRecognition)
r.Get("/logs", u.pageLogs)
@ -4179,3 +4180,14 @@ func (u *UI) actionFaceGalleryDeletePhoto(w http.ResponseWriter, r *http.Request
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"ok": true})
}
func (u *UI) apiDeviceMetrics(w http.ResponseWriter, r *http.Request) {
deviceID := r.URL.Query().Get("device_id")
if deviceID == "" { http.Error(w, "missing device_id", http.StatusBadRequest); return }
dev, ok := u.findDevice(deviceID)
if !ok { http.Error(w, "device not found", http.StatusNotFound); return }
body, code, err := u.agent.Do("GET", dev.IP, dev.AgentPort, "/v1/metrics", nil)
if err != nil { http.Error(w, err.Error(), http.StatusBadGateway); return }
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(body)
}

View File

@ -79,10 +79,10 @@
var body=document.getElementById('metrics-body'),time=document.getElementById('metrics-time');
function load(){
time.textContent='加载中…';
var devs=[{{range .Devices}}{{if .Online}}{ip:"{{.IP}}",port:{{.AgentPort}},name:"{{.DisplayName}}"},{{end}}{{end}}];
var devs=[{{range .Devices}}{{if .Online}}{id:"{{.DeviceID}}",name:"{{.DisplayName}}"},{{end}}{{end}}];
if(!devs.length){body.innerHTML='<span class="muted">无在线设备</span>';return}
Promise.all(devs.map(function(d){
return fetch('http://'+d.ip+':'+d.port+'/v1/metrics',{headers:{'X-RK-Token':''}}).then(function(r){return r.json()}).catch(function(){return null}).then(function(m){return{name:d.name,data:m}});
return fetch('/ui/api/device-metrics?device_id='+d.id).then(function(r){return r.json()}).catch(function(){return null}).then(function(m){return{name:d.name,data:m}});
})).then(function(r){
var html='';
r.forEach(function(item){