You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native/Expo调用Grafana API无法暂停AWS托管告警问题

问题

在React Native + Expo开发的移动端应用中,通过Grafana API对AWS托管的Grafana工作区告警执行暂停/恢复操作时,Postman测试状态切换正常,但应用内仅能恢复告警,无法完成暂停操作。控制台显示尝试暂停(传入paused: true)时,返回提示"Alert is already un-paused",但实际告警处于未暂停状态;恢复操作(传入paused: false)则正常。

相关代码如下:

const changeAlertsStatus = (item) => {
  var state = {
    paused: item.state === "paused" ? false : true,
  };

  console.log(state);
  const URL = `${myURL}/api/alerts/${item.id}/pause`; 
  try {
    fetch(URL, {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization: SynergyGrafanaApiKey,
      },
      body: state,
    })
      .then((response) => response.json())
      .then((json) => {
        console.log(json);
        getAlertsList();
      });
  } catch (error) {
    console.log(error.message);
  }
};

问题原因与解决方案

核心原因

React Native的fetch API不会自动将JavaScript对象序列化为JSON字符串,直接传递state对象作为请求体时,实际发送的内容格式不符合Grafana API的要求,导致API未能正确识别paused: true的参数,从而误判告警状态。而Postman会自动处理JSON请求体的序列化,因此测试正常。

修复步骤

  1. 序列化请求体:将body: state修改为body: JSON.stringify(state),确保请求体是标准的JSON格式。
  2. 添加请求状态校验:新增HTTP响应状态码校验,方便排查后续请求错误。
  3. (可选)确认状态判断逻辑:验证item.state的取值是否与Grafana返回的状态值完全匹配(比如是否存在大小写差异),确保状态切换逻辑正确。

修改后的代码

const changeAlertsStatus = (item) => {
  const state = {
    paused: item.state === "paused" ? false : true,
  };

  console.log(state);
  const URL = `${myURL}/api/alerts/${item.id}/pause`; 
  fetch(URL, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: SynergyGrafanaApiKey,
    },
    body: JSON.stringify(state),
  })
    .then((response) => {
      // 校验HTTP响应状态
      if (!response.ok) {
        throw new Error(`请求失败,状态码:${response.status}`);
      }
      return response.json();
    })
    .then((json) => {
      console.log(json);
      getAlertsList();
    })
    .catch((error) => {
      console.log(error.message);
    });
};

内容的提问来源于stack exchange,提问作者Yoslandy Mesa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 00:25:16