如何解决关于节点获取 api 的问题具体来说,当尝试使用 fetch 来检索 JSON 数据时
下面的代码可以毫无问题地检索 JSON 数据。
app.get('/startgame',(req,res) => {
res.send('Welcome To The Start Of The Game')
fetch("https://deckofcardsapi.com/api/deck/new/shuffle/deck_count=1")
.then(res => res.json())
.then(json => console.log(json))
})
当我执行 console.log(json) 时,下面的代码返回 undefined。这两个代码块之间的唯一区别是底部代码块上的波浪括号。我想知道为什么会发生这种情况。我的理解是它们都应该产生相同的结果。
app.get('/startgame',res) => {
res.send('Welcome To The Start Of The Game')
fetch("https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1")
.then((res) => {res.json()})
.then((json) => {console.log(json)})
})
解决方法
原因是这个语法:
() => foo()
简称:
() => { return foo(); }
在您的代码中的这一行:
.then((res) => { res.json() })
您不再返回 res.json()
的结果。使用大括号时需要明确使用 return
:
.then((res) => { return res.json(); })
相当于:
.then((res) => res.json())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。