Next.js Discord

Discord Forum

Issue with API

Unanswered
Terrier Brasileiro posted this in #help-forum
Open in Discord
Terrier BrasileiroOP
Hello, I've ran into an issue with API requests. I'm trying to fetch data from my API, but it won't work. Response status is 404.

Project dir is src/app. API dir src/app/api.

API:
// src/app/api/posts/getAllPosts.ts

import { NextApiRequest, NextApiResponse } from "next";

type ResponseData = {
    message: string
}

const handler = async (req: NextApiRequest, res: NextApiResponse<ResponseData>) => {
    res.status(200).json({ message: 'Hello from Next.js!' })
};

export default handler;

6 Replies

Terrier BrasileiroOP
Fetching source:

// src/app/[lang]/page.tsx
const getData = async () => {
  const postData = {
    method: 'GET',
    headers: {
      "Content-Type": "application/json"
    }
  }
  const data = await fetch(`http://localhost:3000/api/posts/getAllPosts`, postData);
  console.log(data); // Warning: Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported.
}

export default async function HomePage({ params: { lang } }: { params: { lang: Locale } }) {
  const dictionary = await getDictionary(lang);
  const data = await getData();

  return (
    <div className={styles.container}>
      <HeaderContent dictionary={dictionary} />
    </div>
  );
}
Also when going directly to the http://localhost:3000/api/posts/getAllPosts, I'm getting an error page's not found
European sprat
you've mixed up the pages router API format with app router (which looks like you're using based on your directory structure)
look at the docs on route handlers in the app router docs to see how to make an API endpoint
Terrier BrasileiroOP
I've done that, couldn't find a solution, that's why I wrote a post here
Looks like I've found a solution