Code below retrieves the JSON data without any problems.
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))
})
Code below returns undefined when I do console.log(json). The only difference between these two blocks of code are the squiggly brackets on the bottom block of code. I would like to know why exactly is this happening. My understanding is that they should both produce the same result.
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)})
})
The reason is that this syntax:
() => foo()
Is short for:
() => { return foo(); }
On this line in your code:
.then((res) => { res.json() })
you are no longer returning the result of res.json()
. You need to explicitly use return
when you use curly braces:
.then((res) => { return res.json(); })
Which is equivalent to:
.then((res) => res.json())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.