skip to Main Content

I have tried manually routing myself to /api/route (through localhost:3000) and it also gives me the 404 error page not found. I do think this is an error with routing as everything else looks good to me, and I do not think it is an error with my file setup.

RegisterModal.tsx (relevant info)

const onSubmit = useCallback(async() => {
        try {
            setIsLoading(true);
            await axios.post('/api/register', {
                email, password, username, name
            });

            toast.success('Account created.');

            signIn('credentials', {
                email,
                password
            });

            registerModal.onClose();
        } catch (error) {
            console.log(error);
            toast.error('Something went wrong.');
        } finally {
            setIsLoading(false);
        }
    }, [registerModal, email, password, username, name]);

register.ts (all)

import {NextApiRequest, NextApiResponse} from "next";
import bcrypt from "bcrypt";
import prisma from "../../../libs/prismadb";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (req.method != 'POST') return res.status(405).end();

    try {
        const {email, username, name, password} = req.body;
        const hashedPassword = await bcrypt.hash(password, 12);
        const user = await prisma.user.create({
            data: {
                email,
                username,
                name,
                hashedPassword
            }
        });

        return res.status(200).json(user);
    } catch (error) {
        console.log(error);
        return res.status(400).end();
    }
}
```[enter image description here](https://i.stack.imgur.com/NqSR4.png)

current.ts (all)

import {NextApiRequest, NextApiResponse} from "next";
import serverAuth from "../../../libs/serverAuth";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method != ‘GET’) return res.status(405).end();

try {
    const {currentUser} = await serverAuth(req);
    return res.status(200).json(currentUser);
} catch (error) {
    console.log(error);
    return res.status(400).end();
}

}


Not sure why the routing to api/register.ts is not working. Tried changing it to route.ts but that did not fix anything. Here's a look at my directory setup.

```[screenshot of directory layout](https://i.stack.imgur.com/NqSR4.png)

If any of my langauge is unclear I apologize, I am a Computer Science student and I am still learning. This is for my Sophomore Project where I chose to make a clone of a social media site and change it to look uniqe on its own. Having an issue with axios. Thank you for the help!


[photo of error](https://i.stack.imgur.com/x2JFa.png)
[console error](https://i.stack.imgur.com/Pz94E.png)

Tried changing it from register.ts to route.ts, did not work. Unsure of what to do next.

[file organization][1]


  [1]: https://i.stack.imgur.com/2qZJA.png

2

Answers


  1. Chosen as BEST ANSWER

    I fixed it!!!

    const onSubmit = useCallback(async() => {
        try {
            setIsLoading(true);
            await axios.post('/api/register/route', {
                email, password, username, name
            });
    
            toast.success('Account created.');
    
            signIn('credentials', {
                email,
                password
            });
    
            registerModal.onClose();
        } catch (error) {
            console.log(error);
            toast.error('Something went wrong.');
        } finally {
            setIsLoading(false);
        }
    }, [registerModal, email, password, username, name]);
    

    Change what is ABOVE to this:

    const onSubmit = useCallback(async() => {
        try {
            setIsLoading(true);
            await axios.post('/api/register/', {
                email, password, username, name
            });
    
            toast.success('Account created.');
    
            signIn('credentials', {
                email,
                password
            });
    
            registerModal.onClose();
        } catch (error) {
            console.log(error);
            toast.error('Something went wrong.');
        } finally {
            setIsLoading(false);
        }
    }, [registerModal, email, password, username, name]);
    

    The change is VERY subtle, but in await axios.post('/api/register/route/', get rid of "route" because the next routing only points to the name of the DIRECTORY and not the filename. In my case, the filename is route and the directory name is register, so point to REGISTER for this to work.


  2. Because you’re using the app directory, the API handler is a little different from the pages router(which is what the format of register.ts is in).

    In short, the handler function has been replaced by multiple different functions for each of the HTTP methods (GET, POST, etc.). For more information, check out the Next.JS docs page for Route Handlers.

    A function similar to the one below might work to fix the issue that you’re having. Make sure that you put the function in the directory named after the route that you would like to use, as this is also something that has changed from the pages router. Check out the Next.JS docs page on defining routes for more info.

    // /api/register/route.ts
    
    export async function POST(req: NextRequest) {
        try {
            const { email, username, name, password } = await req.json();
            const hashedPassword = await bcrypt.hash(password, 12);
            const user = await prisma.user.create({
                data: {
                    email,
                    username,
                    name,
                    hashedPassword
                }
            });
    
            return NextResponse.json(user);
        } catch (error) {
            console.log(error);
            return NextResponse.json({
                error: "There was an error creating the user."
            }, {
                status: 400,
            });
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search