5

I just started using NEXTJS 13 version and it confused me a little bit.

Well, This is my project structure:

enter image description here

I have a user.ts file inside an api folder that has this code :


const token = process.env.TOKEN;

export async function GET(request: Request) {
    return new Response('Hello, Next.js!');
}

export async function POST(request: Request) {
    const query = `
    query {
      user(login: "MenaiAla") {
          avatarUrl
    }
  `;

    fetch('https://api.github.com/graphql', {
        method: 'POST',
        headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ query }),
    })
        .then((response) => response.json())
        .then((data) => console.log(data));
}

In my page.tsx, I have a from with a submit method:


'use client';

import React from 'react';
import ProfileImage from './components/ProfileImage';
import SearchField from './components/SearchField';

export default function Home() {
    const handleSearch = (event: React.FormEvent) => {
        event.preventDefault();
        fetch('http://localhost:3000/app/api/user', {
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
            },
            body: JSON.stringify({ keyword: 'menaiala' }),
        })
            .then((response) => response.json())
            .then((data) => {
                console.log(data);
            })
            .catch((error) => {
                console.error(error);
            });
    };
    return (
        <form className='inline-flex flex-col' onSubmit={handleSearch}>
            <SearchField />
            <ProfileImage src='' devName='' />
        </form>
    );
}

I get used to using this methodology in the previous versions, but it throws this error:

enter image description here

I tried " /api/user but I got the same error.

What should I change to access the API?

Thank you

1 Answers1

4

With the app folder your route handler file needs to be called route.js|ts. In this case instead of api/user.ts your file structure should be api/user/route.ts. You can read more about it here https://nextjs.org/docs/app/building-your-application/routing/router-handlers#convention

alexortizl
  • 2,125
  • 1
  • 12
  • 27