Next.js Discord

Discord Forum

Route Handler giving 405 Error

Answered
Arinji posted this in #help-forum
Open in Discord
Avatar
ArinjiOP
Heya so i am getting a image from the client, converting it to base 64 and uploading it to imagekit and storing its link and other info in Supabase, However when i call the api route i get a
GET http://localhost:3000/api/uploadImage 405 (Method Not Allowed)

This is my code
Button in Client
onClick={async () => {
                  if (name === "") {
                    setError({ ...error, name: true });
                    return;
                  }
                  if (day === "") {
                    setError({ ...error, day: true });
                    return;
                  }

                  setError({ ...error, name: false, day: false });
                  setLoading(true);
                  if (file == undefined) return;
                  const image = (await toBase64(file)) as string;
                  const data = {
                    file: image.split(",")[1],
                    name: name.replace(/\s+/g, "-").toLowerCase(),
                    day: day,
                    tripId: tripId,
                  };

                  console.log(data);

                  await fetch("/api/uploadImage"),
                    {
                      method: "POST",
                      headers: {
                        "Content-Type": "application/json",
                      },
                      body: JSON.stringify(data),
                    };

                  setLoading(false);
                  router.push(`/trip/${tripId}`);
                }}


PS: Data when i console.log it is
file: 'iVBORw0KGgoAAAANSUhEUgAABaAAAAP4CAYAAAArrVtoAAAACXerJ33iDAAAAAAAKji/wHadIjNRh7u8AAAAABJRU5ErkJggg==', 
name: 'testinggggg', 
day: '1', 
tripId: '286510'


route handler code below since messsage limit
Answered by joulev
look, the fetch statement already ends here
Image
View full answer

40 Replies

Avatar
ArinjiOP
app/api/uploadImage/route.ts
import { imagekit } from "@/utils/imagekitClient";

import { auth } from "@clerk/nextjs";
import { getClerkToken } from "@/utils/supabaseToken";
import { supabaseClient } from "@/utils/supabaseClient";

export async function POST(request: Request) {
  const data: {
    file: string;
    name: string;
    tripId: string;
    day: string;
  } = await request.json();
  const { userId } = auth();
  const token = await getClerkToken();
  const supabase = await supabaseClient(token);

  if (
    !data.name.includes(".jpg") &&
    !data.name.includes(".png") &&
    !data.name.includes(".jpeg")
  )
    data.name = data.name + ".jpg";

  const imageKitFile = await imagekit.upload({
    file: data.file,
    fileName: data.name,
    folder: "/Travel_Note",
    useUniqueFileName: true,
  });

  console.log(imageKitFile);

  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const currentDate = `${year}-${month}-${day}`;

  const name = imageKitFile.name.split(".")[0];

  const SupabaseData = await supabase.from("images").insert({
    id: Math.random().toString(36).substring(2),
    uploaded_at: currentDate,
    tripId: data.tripId,
    userId: userId,
    name: name,
    day: data.day,
    link: imageKitFile.url,
    height: imageKitFile.height,
    width: imageKitFile.width,
    fileId: imageKitFile.fileId,
  });

  console.log(SupabaseData.data, SupabaseData.error);

  return new Response("E");
}


I have added console logs in the route itself so if there was a issue in imagekit and supabase i would see it.. but it seems like the route itself isnt being called. Any idea?


(Adding code here since message limit)
Avatar
ArinjiOP
I don't really know why I'm getting a 405 error tbh lol
Avatar
Kokoni
you used POST in the fetch
Avatar
ArinjiOP
So shld I do put?
Avatar
Kokoni
you made a GET request
GET http://localhost:3000/api/uploadImage 405 (Method Not Allowed)
Avatar
ArinjiOP
But my code has the post method
Avatar
Kokoni
yeah but you are reporting that you can't make a GET request
Avatar
ArinjiOP
Like the client button
Avatar
Kokoni
and your code can makes a POST request
Avatar
ArinjiOP
That's the error I'm getting so .. but yea I didn't see that the error was reporting a get error
Soo.. what shld I change?
Avatar
Kokoni
You said you got an error when making the GET request, right? In your code in the fetch you have put that you can only make with the POST method, edit it and put GET if you want to use the GET.
Avatar
ArinjiOP
No i want a post request, idk why im getting a get error lol
Avatar
Kokoni
await fetch("/api/uploadImage"),
                    {
                      method: "POST", //GET

                      headers: {
                        "Content-Type": "application/json",
                      },
                      body: JSON.stringify(data),
};
ohhh
okay
Avatar
ArinjiOP
because even if that was just an error and the actual thing runs... i shld have gotten the console logs
but im not getting anything logged or anything inserted anywhere
Avatar
Kokoni
but you aren't making a get request?
you are using the browser?
Avatar
ArinjiOP
nope, post request.. lemme show you
await fetch("/api/uploadImage"),
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
thats the button
which calls the api
Avatar
Kokoni
How are you making the request?
thunder client, browser..
Avatar
ArinjiOP
export async function POST(request: Request) {
const data: {
file: string;
name: string;
tripId: string;
day: string;
} = await request.json();

The api
uh browser ig
coz its a website...
Avatar
joulev
look, the fetch statement already ends here
Image
Answer
Avatar
joulev
remove the ) at the end
Avatar
ArinjiOP
oh
Avatar
joulev
GET by default so fetch("/api/uploadImage") makes a GET
Avatar
Kokoni
but if you're accessing the API by the browser the browser makes a GET call, not a POST
Avatar
ArinjiOP
await fetch("/api/uploadImage",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});

better?
Avatar
Kokoni
also see what joulev is telling you
Avatar
ArinjiOP
yea lemme try it
yep it worked
thankyouuu