为何两种fetch POST请求结果不同?token未定义且catch不触发
问题分析与解决
1. 为什么token始终是undefined?
第一个.then()的回调函数里,你调用了response.json()但没有返回它的结果。箭头函数如果用大括号包裹代码块,必须显式写return,否则默认返回undefined。这就导致下一个.then()接收到的参数就是undefined,所以console.log(token)输出undefined。
2. 为什么错误凭证登录时.catch()不触发?
fetch的.catch()只捕获网络层面的异常(比如请求无法发送、DNS解析失败等)。像错误凭证导致的401 Unauthorized这类HTTP状态码错误,属于业务层面的HTTP错误,fetch不会自动将其转为异常,所以不会触发.catch(),需要手动检查响应状态来判断请求是否成功。
修正后的代码
let requestInfo = JSON.stringify({ email: email, password: password, }); let requestOptions = { method: "POST", headers: { 'Content-Type': 'application/json' }, body: requestInfo } fetch('http://url/token', requestOptions) .then(response => { setShowLoading(false); // 手动检查HTTP响应是否成功 if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } // 必须返回解析后的JSON结果,供下一个then使用 return response.json(); }) .then(token => console.log(token)) .catch(error => console.log(error))
关键修正点
- 在第一个
.then()中显式return response.json(),确保后续.then()能拿到解析后的数据。 - 通过
response.ok判断请求是否成功(状态码200-299为成功),非成功状态主动抛出错误,让.catch()能捕获到错误凭证这类场景的异常。
内容的提问来源于stack exchange,提问作者Grant Solomons
相关产品推荐
相关产品推荐

