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

React调用Node.js天气接口报Unexpected token < in JSON错误如何解决?

问题排查及修复方案

1. 前端fetch地址语法错误(直接导致当前报错)

你当前的请求地址少了http后的冒号,错误的地址会导致请求命中404页面,返回的HTML内容以<开头,和你报错的Unexpected token < in JSON at position 0完全匹配。
修正代码:

fetch('http://localhost:8000/getmeteo')

2. useEffect无限调用问题

你当前的useEffect没有传入依赖数组,会导致组件每次渲染都重新发起请求,陷入死循环。修改为只在组件挂载时发起一次请求:

useEffect(() => {
  fetch('http://localhost:8000/getmeteo')
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.log('请求错误:', err)) // 建议加上catch捕获异常
}, []) // 加空依赖数组

3. 后端响应格式优化

Express的res.send会自动推断响应类型,存在识别错误的可能,建议直接用res.json返回JSON格式数据,同时补充错误场景处理:

app.get('/getmeteo', (req, res) => {
    let city = req.query.city;
    request(
        `https://api.openweathermap.org/data/2.5/forecast?q=paris&appid=${apiKey}`,
        function(error, response, body) {
            // 先捕获请求错误
            if(error) {
              return res.status(500).json({msg: '天气接口请求失败'})
            }
            if (response.statusCode === 200) {
                let data = JSON.parse(body);
                res.json(data.list[0].main) // 替换res.send为res.json
            } else {
              res.status(response.statusCode).json({msg: '天气接口返回异常'})
            }
        }
    );
});

4. 跨域问题检查

如果你的前端运行端口(通常React默认是3000)和后端8000端口不一致,会触发浏览器跨域限制,需要在后端安装CORS中间件:

  1. 安装依赖:npm install cors
  2. 在express代码中启用:
const cors = require('cors')
app.use(cors())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:45:02