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

React调用Express爬虫接口前返回undefined 读取description报错如何修复?

错误原因

这个报错是因为你在未校验接口返回值结构的前提下,直接访问了data[0].description,当接口返回的data是空数组、或者请求异常返回非数组结构时,data[0]为undefined,访问它的属性就会抛出类型错误。你遇到的偶现报错大概率是首次触发请求时scraperlink还未赋值,导致后端返回空数组。

前端修复方案

修改你的React请求代码,增加无效请求拦截、错误捕获和返回值校验逻辑:

const [websitedescription, setwebsitedescription] = useState(null)
useEffect(() => {
  // 拦截scraperlink为空的无效请求
  if (!scraperlink) return
  async function scraper() {
    try {
      const response = await fetch(`http://localhost:5000/scraper/${scraperlink}`)
      // 校验HTTP请求状态是否正常
      if (!response.ok) throw new Error('接口请求异常')
      const data = await response.json()
      // 校验返回值是数组且有内容再取值
      if (Array.isArray(data) && data.length > 0) {
        const websitedescription = data[0].description
        const logolink = data[0].favicon
        setwebsitedescription(websitedescription)
      }
    } catch (err) {
      // 可自行添加错误提示逻辑
      console.error('站点信息抓取失败:', err)
    }
  }
  scraper()
}, [scraperlink])

你也可以用ES2020的可选链运算符简化取值逻辑,无需写多层判断:

const websitedescription = data?.[0]?.description
const logolink = data?.[0]?.favicon

可选后端优化

你可以在后端接口增加参数和结果校验,避免前端接收到不符合预期的空结构:

app.get("/scraper/:link", async (req, res) => {
  const {link} = req.params;
  if (!link) return res.status(400).json({msg: '参数link不能为空'})
  const data = await scrapeMetatags(link)
  if (data.length === 0) return res.status(404).json({msg: '未抓取到对应站点信息'})
  res.json(data)
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:15:02