为何使用Fetch API提取GET请求的JSON响应时控制台输出undefined?
为什么我的fetch代码控制台输出undefined?
嘿,我一眼就揪出问题啦!你的fetch调用链里第一个then回调没有返回解析后的Promise,这就是第二个then拿到undefined的核心原因。
问题具体出在这里:
看你这段代码片段:
.then(response=>{ response.json() })
你用大括号包裹了箭头函数的逻辑,但没有写return语句。箭头函数如果用大括号包裹代码块,就必须显式返回值,否则默认会返回undefined。这就导致下一个then接收到的不是解析后的JSON数据,而是undefined。
修正后的代码(两种可选写法):
方式1:去掉大括号,箭头函数会自动返回response.json()的结果:
const url = window.location.href.split('/') const url1 = url[6].substring(2) fetch(`http://localhost:8080/apiget/userinfo/${url1}`) .then(response=> response.json()) // 去掉大括号,自动返回Promise .then(json=>console.log(json)) .catch(error=>console.log('something went wrong'))
方式2:保留大括号,显式添加return语句:
const url = window.location.href.split('/') const url1 = url[6].substring(2) fetch(`http://localhost:8080/apiget/userinfo/${url1}`) .then(response=>{ return response.json() }) // 显式返回解析Promise .then(json=>console.log(json)) .catch(error=>console.log('something went wrong'))
额外说明:
response.json()方法会返回一个Promise,这个Promise会在JSON解析完成后resolve为对应的数据。只有把这个Promise传递给下一个then,后续的回调才能拿到你预期的JSON内容。你之前的代码没有返回这个Promise,所以下一个then自然接收到undefined啦。
内容的提问来源于stack exchange,提问作者yusufa22
相关产品推荐
相关产品推荐

