Grafana持续请求NestJS后端/api/live/ws接口引发404错误的问题咨询
你好,针对你遇到的问题,我来帮你拆解原因和可行的解决方案:
一、为什么Grafana会请求/api/live/ws?
这个/api/live/ws是Grafana Live的核心WebSocket端点,Grafana Live是Grafana内置的实时通信功能,用来实现仪表盘数据实时刷新、告警推送、多用户协作同步等场景。默认情况下Grafana会启用这个功能,当你打开Grafana页面时,前端会自动尝试建立这个WebSocket连接。
出现请求打到NestJS后端的情况,大概率是因为部署配置存在路径冲突:比如Grafana和NestJS共享了同一个域名/端口,反向代理规则把/api路径都指向了NestJS,导致Grafana前端发起的/api/live/ws请求被错误转发到NestJS,最终因找不到对应路由抛出404。
二、能不能禁用这个请求?怎么解决?
当然可以禁用,也可以通过配置修正请求路径,这里给你几个实用方案:
方案1:彻底禁用Grafana Live功能
你之前修改grafana.ini没生效,可能是配置项没写对或者没重启Grafana。正确的配置方式是:
找到grafana.ini中的[live]区块,添加或修改:
[live] enabled = false
保存配置后必须重启Grafana服务,这样Grafana前端就不会再发起/api/live/ws的请求了。
方案2:修正反向代理/路径配置(推荐,若需保留Live功能)
如果还想使用Grafana Live的实时能力,你需要调整反向代理规则,把/api/live/ws路径单独转发到Grafana的服务地址,而非NestJS。比如用Nginx的话,可以添加这样的规则:
location /api/live/ws { proxy_pass http://你的Grafana服务地址; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location /api { proxy_pass http://你的NestJS服务地址; }
这样就能把Grafana Live的WebSocket请求正确转发到Grafana,其他/api请求交给NestJS处理。
方案3:在NestJS中临时处理该路由
如果暂时不想调整Grafana或反向代理,也可以在NestJS中添加一个空路由来捕获/api/live/ws请求,避免抛出404错误:
// 在某个模块的控制器中添加 @Controller('api/live') export class LiveWsController { @Get('ws') handleWs() { // 直接返回空响应或关闭连接 return {}; } }
附:你提供的NestJS错误日志
exception NotFoundException: Cannot GET /api/live/ws at callback (/Users/hraschan/private/gymble-nestjs-backend/node_modules/@nestjs/core/router/routes-resolver.js:77:19) at /Users/hraschan/private/gymble-nestjs-backend/node_modules/@nestjs/core/router/router-proxy.js:9:23 at Layer.handle [as handle_request] (/Users/hraschan/private/gymble-nestjs-backend/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/Users/hraschan/private/gymble-nestjs-backend/node_modules/express/lib/router/index.js:328:13) at /Users/hraschan/private/gymble-nestjs-backend/node_modules/express/lib/router/index.js:286:9 at Function.process_params (/Users/hraschan/private/gymble-nestjs-backend/node_modules/express/lib/router/index.js:346:12) at next (/Users/hraschan/private/gymble-nestjs-backend/node_modules/express/lib/router/index.js:280:10) at LoggerMiddleware.use (/Users/hraschan/private/gymble-nestjs-backend/src/core/middleware/logger.middleware.ts:29:5) at /Users/hraschan/private/gymble-nestjs-backend/node_modules/@nestjs/core/router/router-proxy.js:9:23 at Layer.handle [as handle_request] (/Users/hraschan/private/gymble-nestjs-backend/node_modules/express/lib/router/layer.js:95:5) { response: { statusCode: 404, message: 'Cannot GET /api/live/ws', error: 'Not Found' }, status: 404, options: {} }
备注:内容来源于stack exchange,提问作者maxi hraschan

