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

React中如何用Fetch API带参数发起GET请求并解决404错误?

问题解决:React中带参数的GET请求404错误修复

核心错误分析

你的404错误根源是前端URL拼接格式完全错误,同时存在Fetch API的使用误区:

  1. URL里的:?{$City1}是无效写法,后端用的是路由参数/:city_name,需要直接把城市名作为路径的一部分拼接
  2. 前端请求头里加Access-Control-Allow-Origin完全多余,这个是后端需要返回的响应头,前端请求添加不生效
  3. 未处理城市名中的特殊字符(比如空格、中文),可能导致请求路径解析异常

修正后的前端代码

const City1 = useSelector((state) => state.City); // 从Redux获取城市名

// 用模板字符串拼接合法URL,同时对城市名编码处理特殊字符
const requestUrl = `http://xxxx.xxxx.xxxx.xxxx/xxxx/${encodeURIComponent(City1)}`;

fetch(requestUrl, {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json', // GET请求可省略该头,保留也不影响
  },
})
  .then((response) => {
    if (!response.ok) {
      throw new Error(`请求失败:${response.status}`);
    }
    return response.json();
  })
  .then((userData) => {
    console.log('获取到的数据:', userData);
    // 这里添加你的业务逻辑处理代码
  })
  .catch((error) => {
    console.error('请求出错:', error);
  });

额外注意事项

  • 确认后端路由的挂载路径:如果后端的router.get('/:city_name')是挂载在/xxxx下,当前URL写法正确;如果是挂载在根路径,URL要改成http://xxxx.xxxx.xxxx.xxxx/${encodeURIComponent(City1)}
  • 若后续改用查询参数(比如?city=北京),后端需调整为router.get('/', (req, res) => { const city = req.query.city; ... }),前端URL对应写成http://xxxx.xxxx.xxxx.xxxx/xxxx?city=${encodeURIComponent(City1)}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 20:42:47