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

Django服务器无法接收React Axios发送的GET请求数据

问题:React Axios GET请求无法向Django服务器传递数据

在React应用中使用Axios发送GET请求到Django服务器时,前端无报错,但服务器日志显示接收的是空对象{}。其他组件的请求均正常,已排除CORS问题。

React Axios请求代码

// PrivateAxios instance to send api request
const axiosPrivate = useAxiosPrivate();
const handleSearch = async () => {
  const data = JSON.stringify({ from_company: keyWord });
  try {
    const response = await axiosPrivate.get(SEARCH_URL, data);
    console.log(response);
    setRecords(response?.data);
  } catch (err) {
    if (!err?.response) {
      console.log("NO SERVER RESPONSE");
    } else {
      console.log("SOMETHING WRONG");
    }
  }
};

服务器日志

{} <-- Prints the request.data as an empty object
"GET /api/find_many/ HTTP/1.1" 200 6276

Postman/Thunder Client测试结果

{'from_company': 'Jethmal Paliwal'}  <-- Prints the request.data correctly
"GET /api/find_many/ HTTP/1.1" 200 2284

已确认请求头设置正确(Content-Type: application/json、withCredentials: true),尝试过直接传入对象、JSON.stringify处理数据均无效。


解决方案

核心问题是GET请求不符合HTTP规范中携带请求体的定义:Axios的get方法第二个参数是配置对象而非请求数据,同时Django会忽略GET请求的请求体,导致无法获取数据。

方案1:使用URL查询参数传递数据

修改React代码,通过params字段传递查询参数:

const handleSearch = async () => {
  try {
    const response = await axiosPrivate.get(SEARCH_URL, {
      params: { from_company: keyWord }
    });
    console.log(response);
    setRecords(response?.data);
  } catch (err) {
    if (!err?.response) {
      console.log("NO SERVER RESPONSE");
    } else {
      console.log("SOMETHING WRONG");
    }
  }
};

对应Django后端需要从request.query_params中获取数据:

# Django视图示例
from_company = request.query_params.get('from_company')

方案2:改用POST请求传递数据

如果业务逻辑确实需要通过请求体传递数据,将请求方式改为POST:

const handleSearch = async () => {
  try {
    const response = await axiosPrivate.post(SEARCH_URL, {
      from_company: keyWord
    });
    console.log(response);
    setRecords(response?.data);
  } catch (err) {
    if (!err?.response) {
      console.log("NO SERVER RESPONSE");
    } else {
      console.log("SOMETHING WRONG");
    }
  }
};

同时确保Django后端视图支持POST方法,并从request.data中读取数据。


内容的提问来源于stack exchange,提问作者Rahul Kumar S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:20:43