Search code examples
next.jsfetch

fetch api is not working in Next js. giving error


NEXT.js

const API_KEY = process.env.API_KEY

import React from 'react'

const Home = async() => {
  const apiUrl = `https://api.themovie.org/3/movie/top_rated$?api_key=${API_KEY}&language=en-US&page=1`;

  const res = await fetch(apiUrl);
  console.log(res)
  try {

  if (!res.ok) {
    throw new Error('Failed to fetch data');
  }

  const data = await res.json();
  const results = data.results;
  console.log(results);
} catch (error) {
  console.error('Error fetching data:', error.message, 
"," ,error.response);
}

  return (
    <div>Home</div>
  )
}

export default Home

I tried the api on postman, and it worked. it looks the error started from the fetch method, above try-catch block. what's the problem here?


Solution

  • Looks like theres a typo in your api url, should be api.themoviedb.org.