JavaScript Fetch POST请求无法接收API响应问题排查
问题根因
一共两个bug,前后端各占一个:
- 前端把
async/await和.then()/.catch()混写,而且.then()回调里只打印了response,没有把response对象return出去,导致fetchData变量实际拿到的是undefined。后续执行await fetchData.json()时,相当于调用undefined上的json方法,会直接抛出类型错误,而这个错误不在之前的catch捕获链里,所以控制台不会打印你预期的响应或者报错日志。 - 后端逻辑有分支缺失:当入参
code为空字符串时,代码不会进入if (code != "")的判断块,也没有任何兜底返回,请求会一直挂在pending状态直到超时,前端自然收不到响应。
修复方案
前端修复后代码
统一用async/await写法,不要混写promise链,同时补上fetch的状态判断——fetch只有网络故障才会抛错,4xx、5xx这类HTTP错误不会自动进catch,需要手动判断:
const fetchPdtDetails = async (code) => { const url = `${api}data/pdtDetails`; const params = { data: code }; try { const response = await fetch(url, { method: "POST", cache: "no-cache", headers: { "Content-Type": "application/json" }, body: JSON.stringify(params), }); if (!response.ok) { throw new Error(`请求异常,状态码:${response.status}`); } console.log("原始响应:", response); const data = await response.json(); console.log("解析后数据:", data); return data; } catch (err) { console.log("请求出错:", err); throw err; } };
后端修复后代码
补全所有逻辑分支的响应返回,不管参数校验是否通过、代码执行到哪个分支,都要给前端返回结果:
router.post("/pdtDetails", async (req, res) => { try { const code = req.body.data; if (!code) { return res.status(400).json({ message: "入参code不能为空" }); } const sql = `SELECT name , category FROM product_master WHERE code=$1`; const get = await pool.query(sql, [code]); console.log(get.rows); return res.json(get.rows); } catch (err) { console.error("接口执行错误:", err); return res.status(500).json({ message: err.message }); } });
额外注意点
- 不要在async函数里随意混写
.then()链,尤其是then的回调里如果不手动return需要的值,外层await拿到的永远是undefined,很容易出隐蔽bug。 - 写后端接口时要检查所有逻辑分支,哪怕是参数非法、查询无结果的场景,都必须返回明确的HTTP响应,不然请求会一直挂起。
- fetch和常用的axios类库行为有差异:404、500、403这类业务错误状态码,不会触发catch,必须手动通过
response.ok字段判断请求是否成功。
内容的提问来源于stack exchange,提问作者Maya
相关产品推荐
相关产品推荐

