I'm using express router in Node and I'm trying to render a page with some data which I get from fetching from an API. However, I get absolutely no results back and it's not the API fault. I checked in console manually and it returns results as expected.
Here's my code:
router.get('/dashboard', ensureAuth, async (req, res) => {
try {
const resp = await fetch("https://api.tvmaze.com/shows?page=1")
const respData = await resp.json()
res.render('dashboard', {
name: req.user.firstName,
image: req.user.image,
shows: respData
})
} catch (error) {
res.render('dashboard', {
name: req.user.firstName,
image: req.user.image
})
}
})
EDIT: Here's the view which is being rendered:
<body>
{{#if shows}}
{{#each shows}}
<img src="{{image.original}}" alt="{{name}}" />
<div class="movie-info">
<h3>{{name}}</h3>
<span>{{weight}}</span>
</div>
{{/each}}
{{else}}
<p>No shows available.</p>
{{/if}}
</body>
I've searched online but I can't find an explanation for where the issue lies here. If this is a duplicate, please redirect me to the original. Thanks.
CodePudding user response:
You can't use fetch
inside node because it's only available in the browser. If you want to make an HTTP request from a node app use axios
or node-fetch