0

I'm new to fastify and nodejs I would like to create a route, allowing me to retrieve the information of the top 1 film thanks to the themoviedb API

First, I have to get the first movie that sends back the road 'https://api.themoviedb.org/3/discover/movie " then retrieve the film information using the movie / id route of themoviedb

I tried to do this

import fastify from 'fastify';
import dotenv from 'dotenv'
dotenv.config();
import got from 'got';

const app = fastify();
app.get('/movies/top1', async (request, reply) => {
  let response;
  try {
    response = await got('https://api.themoviedb.org/3/discover/movie?api_key='+process.env.API_KEY+'&sort_by=vote_average.asc');
  } catch (err) {
    console.log(err)
  }
  let responseMovie;
  try {
    responseMovie = await got('https://api.themoviedb.org/3/movie/'+ response.body.results[0].id +'?api_key='+process.env.API_KEY);
  } catch (err) {
    console.log(err)
  }
  reply.send(responseMovie.body);
});
app.listen(8000);

But I have an error "Cannot read properties of undefined (reading '0')" I would like to execute the second request when the first is finished and return the result of the second request HOw to do this please ?

Cohchi
  • 543
  • 3
  • 9
  • 19
  • The error has nothing to do with the order of the statements, but more with what is returned by the API. Please provide additional information about what is returned, because the error states, that the `results`property is undefined. – Timon Dec 18 '21 at 16:36
  • the api returns an object with results as an array (https://developers.themoviedb.org/3/discover/movie-discover) – Cohchi Dec 18 '21 at 16:42
  • please provide a plain result of the api response. Put a `console.log(response)` after the first request – Timon Dec 18 '21 at 16:45
  • it's a very very long thing but there is the console.log(response.body) {"page":1,"results":[{"adult":false,"backdrop_path":null,"genre_ids":[18],"id":91,"original_language":"en","original_title":"A Perfect Child","overview":"A teenage girl whose parents were killed in a car accident begins to discover some suspicious secrets about the orphanage she is sent to. She gets in way over her head as she digs deeper.Australia","popularity":0,"poster_path":null,"release_date":"2017-07-06","title":"A Perfect Child","video":false,"vote_average":0,"vote_count":0}],"total_pages":1,"total_results":1} – Cohchi Dec 18 '21 at 16:51
  • I think the error lies in your understanding of the "got" library. According to their docs in order to access the JSON payload you will need to do something like this: `const {data} = await response.json()`. Ensure that you are getting the correct information back from the first request with `console.log(data)` as @Timon suggests. – Nathan Hellinga Dec 29 '21 at 16:42

0 Answers0