skip to Main Content

I want to create api in my website like /api/popular-movie
this is my file structure
enter image description here

and this is route.ts

import { NextResponse } from "next/server";

import Redis from "ioredis";
type Result = {
  data: string;
  type: string;
  latency: number;
};

let redis = new Redis(process.env.REDIS_URL as string);

export async function GET() {
  let start = Date.now();
  const cacheKey = "popular_movies";
  let cache = await redis.get(cacheKey);
  cache = JSON.parse(cache as string);
  let result: Partial<Result> = {};
  if (cache) {
    console.log("loading from cache");
    result.data = cache;
    result.type = "redis";
    result.latency = Date.now() - start;
    return NextResponse.json(result);
  } else {
    console.log("loading from api");
    start = Date.now();
    return fetch(
      `https://api.themoviedb.org/3/movie/popular?api_key=${process.env.NEXT_PUBLIC_API_KEY}&page=1`
    )
      .then((r) => r.json())
      .then((data) => {
        result.data = data;
        result.type = "api";
        result.latency = Date.now() - start;
        redis.set(cacheKey, JSON.stringify(result.data), "EX", 60);
        return NextResponse.json(result);
      });
  }
}

but when I want to fetch data from /api/popular-movie I got error

TypeError: Failed to parse URL from /api/popular-movie
at Object.fetch (D:nextjs-projectfull-stack-projectnode_modulesnextdistcompiledundiciindex.js:1:26686)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async getData (webpack-internal:///(sc_server)/./app/page.tsx:14:17)
at async Home (webpack-internal:///(sc_server)/./app/page.tsx:21:18) { [cause]:
TypeError [ERR_INVALID_URL]: Invalid URL
at new NodeError (node:internal/errors:387:5)

and this is my request:

async function getData() {
  const res = await fetch(`/api/popular-movie`);

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

  return res.json();
}

I do not know when I go to localhost:3000/api/popular-movie it tells me the page has not found.

2

Answers


  1. If you call api from a page that is in another folder like pages/somepage/pageThatYouCall you have to route the api like this:

    ../api/theApiPage
    
    Login or Signup to reply.
  2. it might be bacause you are on windows and your folder separator is backslash instead of forward slask /. check this out next-config-js/trailingSlash

    Open next.config.js and add the trailingSlash config:

    next.config.js
    
    module.exports = {
      trailingSlash: true,
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search