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

使用fetch获取Rails的/notifications.json后,如何解析响应提取数据?

Rails + StimulusJS 处理fetch响应获取JSON数据的正确方式
  • 问题核心:fetch API返回的是Response对象,并非直接的JSON数据。response.json()本身是一个Promise,必须等待它解析完成才能拿到实际的哈希数组。

方式1:使用async/await(推荐,代码更清晰)

在Stimulus控制器中这样实现:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  connect() {
    this.loadNotifications()
  }

  async loadNotifications() {
    try {
      const response = await fetch('/notifications.json')
      // 先校验响应是否成功
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`)
      }
      const notifications = await response.json() // 此处获取目标哈希数组
      console.log(notifications)
      // 后续可添加通知渲染逻辑
    } catch (error) {
      console.error('加载通知出错:', error)
    }
  }
}

方式2:使用Promise链式调用

如果偏好链式写法,也可以这样处理:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  connect() {
    fetch('/notifications.json')
      .then(response => {
        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`)
        }
        return response.json() // 返回解析JSON的Promise
      })
      .then(notifications => {
        console.log(notifications) // 拿到目标哈希数组
        // 处理通知渲染逻辑
      })
      .catch(error => {
        console.error('加载通知出错:', error)
      })
  }
}

关键注意点

  • 必须检查response.ok:即使后端返回401、500这类错误状态码,fetch不会直接抛出错误,只有网络层面的失败才会进入catch,所以要手动判断HTTP状态码是否在2xx成功范围内。
  • 不要直接打印response.json():它是一个Promise对象,而非解析后的数据,必须等待其resolve后才能获取结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:10:45