I am creating a simple movie discussion forum. The user has a profile where they can enter in their favourite films separated by a comma. The backend route calls the OMDB API and returns the JSON objects for the movies which the details such as poster, title and other applicable information will be shown.
I have created a backend route using Express to get the information. I successfully managed to get a single movie from OMDB and return it as a JSON object on Postman.
However, when I try to map through the favouriteFilms array, the object returned is (or seems to be) empty.
The code below makes a get request to '/movies', takes in the auth JWT middleware created and an async req, res callback.
A profile variable is declared to get the profile of the user by id.
Using Promise.all(), a films variable is set to map through all the profile.favouriteFilms array and for each film, return the information from the OMDB request and then res.json(films.data)
router.get('/movies', auth, async (req, res) => {
try {
const profile = await Profile.findOne({ user: req.user.id });
const films = Promise.all(
profile.favouritefilms.map((film) =>
axios.get(
`http://www.omdbapi.com/?t=${film}&apikey=${config.get('OMDBkey')}`
)
)
);
res.json(films.data);
} catch (error) {
console.error(error.message);
res.status(500).send('Server Error');
}
});
As stated above, the output on Postman is empty.
You should handle result of Promise.all by another .then() method. See below:
const profile = await Profile.findOne({ user: req.user.id });
const films = Promise.all(
profile.favouritefilms.map((film) =>
axios.get(
`http://www.omdbapi.com/?t=${film}&apikey=${config.get('OMDBkey')}`
)
)
).then(films => res.json(films.map(film => film.data))