ReactJS中使用Fetch请求:响应成功但response.ok === false
问题排查:React Fetch请求Express后端报错(Postman正常)
核心问题
前端Fetch请求的配置错误,导致后端无法正确解析请求体,最终返回非2xx状态码触发错误捕获。
错误原因
你的Fetch配置中直接使用了contentType: 'application/json',但Fetch API的options参数里没有这个属性,正确的做法是将请求头放在headers对象中,并且键名应为Content-Type(符合HTTP头的大小写规范)。
因为缺少正确的Content-Type请求头,后端的express.json()中间件无法解析JSON格式的请求体,导致接口返回非成功状态码,进而触发前端的throw new Error逻辑。
修正后的前端代码
const submitForm = (event) => { event.preventDefault(); fetch(`${process.env.REACT_APP_BASE_API_URL}/users/login`, { body: JSON.stringify({ username, password }), headers: { // 改为headers对象包裹请求头 'Content-Type': 'application/json' // 正确的请求头键名 }, method: 'POST' }) .then((response) => { console.log(response); if (response.ok) return response.json(); throw new Error('Something went wrong'); }) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); };
额外验证点
- 确认
process.env.REACT_APP_BASE_API_URL的值正确,需包含后端路由的/api前缀对应的基础路径,比如后端挂载路由为/api,则环境变量应设为http://localhost:3000,拼接后请求地址为http://localhost:3000/api/users/login - 检查后端
/users/login接口逻辑,确保请求体解析正常时返回2xx状态码(如200)
内容的提问来源于stack exchange,提问作者namln-hust
相关产品推荐
相关产品推荐

