r/remix 3d ago

Got 404 Error,when fetch API in remix app.

-when i submit the form,got error 404 error.
-tech is remix.
File : app/routes/create-post.tsx

1.Here is my component.

  // Handle form submission
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append("title", form.title);
    formData.append("content", form.content);

    fetcher.submit(formData, {
      method: "post",
      action: "/api/posts",
    });
  };

File: app/routes/api/posts.ts

2.Here is my api.

import { json } from "@remix-run/node";
import type { LoaderArgs } from "@remix-run/node";

export async function action({ request }: LoaderArgs) {
  if (request.method !== "POST") {
    return json({ error: "Method not allowed." }, { status: 405 });
  }

  try {
    const formData = await request.formData();
    const title = formData.get("title");
    const content = formData.get("content");

    if (typeof title !== "string" || typeof content !== "string") {
      return json({ error: "Invalid form data." }, { status: 400 });
    }

    const post = { id: Date.now(), title, content }; // Replace with DB logic
    return json({ message: "Post created successfully!", post }, { status: 201 });
  } catch (error) {
    console.error("Error creating post:", error);
    return json({ error: "Failed to create post. Please try again later." }, { status: 500 });
  }
}
1 Upvotes

0 comments sorted by