使用fetch API请求数据时报TypeError: res.json is not a function错误求助
问题原因
- fetch API调用后返回的是Promise对象,你的代码中调用fetch时没有添加
await关键字等待异步操作完成,所以赋值给res的是处于pending状态的Promise实例,而非请求返回的Response响应对象,自然不存在json方法,因此触发TypeError: res.json is not a function报错。 - 额外存在的逻辑隐患:当前的状态码判断语句
!res.status === 200存在运算符优先级错误,!的优先级高于===,实际执行时会先对res.status取反再和200做比对,永远不会得到true的判断结果,无法正确捕获非200的异常请求状态。
修复方案
给fetch调用添加await关键字,同时修正状态码判断逻辑,修改后代码如下:
const DefaultLayout = () => { let history = useHistory() const callHomePage = async () => { try { // 新增await等待fetch异步执行完成,拿到Response对象 const res = await fetch('http://localhost:4000/api/authenticate', { method: 'GET', headers: { Accept: 'application/json', 'Content-type': 'application/json', }, credentials: 'include', }) console.log(res) const data = await res.json() console.log(data) // 修正状态码判断逻辑 if (res.status !== 200) { const error = new Error(res.error) throw error } } catch (err) { console.log(err) history.push('login') } }
内容的提问来源于stack exchange,提问作者Sachin Maharjan
相关产品推荐
相关产品推荐

