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

React如何通过fetch或axios获取Express端从MongoDB查询的course2数据

解决步骤

第一步:修改Express服务端,暴露数据接口

你当前的服务端仅在启动时打印了course2数据,没有提供可供前端调用的HTTP接口,需要先新增GET接口:

// 在Express代码中新增以下内容,放在app.listen之前即可
app.get('/api/courses', async (req, res) => {
  try {
    const course2 = await Course.find()
    // 把查询到的数据以JSON格式返回给请求方
    res.json(course2)
  } catch (err) {
    res.status(500).json({ error: '数据查询失败' })
  }
})

修改后重启Express服务,访问http://localhost:5000/api/courses如果能看到JSON格式的数据,说明接口配置成功。

第二步:React中使用原生fetch获取数据

以下是函数组件的实现示例,直接引入到你的React项目中即可使用:

import { useEffect, useState } from 'react'

function SensorData() {
  const [dataList, setDataList] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  // 组件挂载时自动发起请求
  useEffect(() => {
    const getCourseData = async () => {
      try {
        const res = await fetch('http://localhost:5000/api/courses')
        if (!res.ok) throw new Error(`请求错误:${res.status}`)
        const courseData = await res.json()
        setDataList(courseData)
      } catch (err) {
        setError(err.message)
      } finally {
        setLoading(false)
      }
    }
    getCourseData()
  }, [])

  if (loading) return <div>数据加载中</div>
  if (error) return <div>加载失败:{error}</div>

  return (
    <div>
      <h2>传感器数据列表</h2>
      {dataList.map((item, idx) => (
        <div key={idx}>
          <p>温度:{item.temp1}℃</p>
          <p>湿度:{item.hum1}%</p>
          <p>采集时间:{new Date(item.date).toLocaleString()}</p>
          <hr />
        </div>
      ))}
    </div>
  )
}

export default SensorData

第三步:可选的axios实现方案

如果使用axios需要先安装依赖:npm install axios
替换上述组件useEffect中的请求逻辑即可:

import axios from 'axios'

// 仅替换useEffect内的代码即可,其他逻辑和fetch版本一致
useEffect(() => {
  const getCourseData = async () => {
    try {
      setLoading(true)
      // axios会自动解析返回的JSON数据,无需手动调用.json()
      const res = await axios.get('http://localhost:5000/api/courses')
      setDataList(res.data)
    } catch (err) {
      setError(err.response?.data?.error || err.message)
    } finally {
      setLoading(false)
    }
  }
  getCourseData()
}, [])

注意事项

  • 确保Express服务和React开发服务同时运行,你已经配置了CORS跨域规则,不会出现跨域拦截问题
  • 项目上线部署时,需要把请求地址中的http://localhost:5000替换为线上服务的实际地址

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:54:02