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

React调用HereUS API获取关注者信息流时请求失败问题排查

解决React fetch请求HereUS API返回400 Bad Request的问题

你遇到的问题是Python脚本能正常请求API,但React用fetch发送POST请求时返回400错误,服务器返回HTML而非预期的JSON。下面是几种排查和解决的方向:

1. 核对请求数据格式是否与Python脚本一致

很多时候服务器实际期望的是application/x-www-form-urlencoded格式(表单数据),而非JSON。如果你的Python脚本用requests.post时传的是data参数(而非json参数),那实际发送的是表单格式,和React里的JSON格式不匹配,导致服务器无法解析请求。

解决方法:改用FormData发送请求:

const formData = new FormData();
formData.append('email', 'username@domain');
formData.append('password', 'password');

fetch('https://hereus.pythonanywhere.com/API/FEED_FOLLOWS', {
  method: 'POST',
  body: formData
})
.then(res => {
  if (!res.ok) throw new Error(`Status: ${res.status}`);
  return res.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));

2. 添加匹配Python脚本的请求头

Python的requests库会自动添加一些默认请求头(比如User-Agent),而fetch的默认头可能和它不同,部分服务器会以此判断请求合法性。

解决方法:复制Python脚本里的请求头到fetch中,比如添加User-Agent:

fetch('https://hereus.pythonanywhere.com/API/FEED_FOLLOWS', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'User-Agent': 'python-requests/2.28.1' // 替换为你Python脚本里的实际User-Agent
  },
  body: JSON.stringify({
    email: 'username@domain',
    password: 'password'
  })
})
.then(res => {
  if (!res.ok) throw new Error(`Status: ${res.status}`);
  return res.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));

3. 确保URL与Python脚本完全一致

检查URL是否包含末尾的斜杠、大小写是否完全匹配,部分服务器对URL的格式敏感,不匹配会导致重定向并返回HTML错误页。

4. 优化错误排查流程

修改fetch代码,先检查响应状态,非成功状态时先获取文本内容,避免直接解析JSON导致的语法错误,能更直观看到服务器的错误提示:

fetch('https://hereus.pythonanywhere.com/API/FEED_FOLLOWS', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    email: 'username@domain',
    password: 'password'
  })
})
.then(res => {
  if (!res.ok) {
    return res.text().then(text => {
      throw new Error(`请求失败: ${res.status}\n服务器返回: ${text}`);
    });
  }
  return res.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));

内容的提问来源于stack exchange,提问作者Çağan Mert İŞLEK

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:05:24