kevin sierra castro
kevin sierra castro

Reputation: 1

I have a POST 404(Not Found) error, I can't find a way to fix it

This is a next js project, I am using openai api to make my chat bot and the error I get is:

POST http://localhost:3000/api/generate/route 404 (Not Found)

By the way I'm new to the backend part :D I hope I can receive a push from you, thank you!

in src>app>api>generate>route.tsx

import { NextResponse } from "next/server";
import OpenAI from "openai";

const openai = new OpenAI();

export async function POST(request: any) {
  const body = await request.json();
  if (!body.content || body.content.length === 0) {
    return NextResponse.json("prompt is required", { status: 400 });
  }
  try {
    const completion = await openai.chat.completions.create({
      messages: [
        { role: "system", content: "You are a movie recommender" },
        { role: "user", content: body.content },
      ],
      model: "gpt-3.5-turbo-instruct",
      temperature: 0.7,
      max_tokens: 60,
    });
    return NextResponse.json(completion.choices[0].message.content);
  } catch (error) {
    return NextResponse.json(
      { error: "internal server error" },
      { status: 500 }
    );
  }
}

in src>app>page.tsx

"use client";
import { useState } from "react";
export default function Home() {
  const [prompt, setPrompt] = useState<string>("");
  const [result, setResult] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(false);

  const onSubmit = async (e: any) => {
    e.preventDefault();
    setLoading(true);
    try {
      const response = await fetch("/api/generate", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ content: prompt }),
      });

      const data = await response.json();
      setResult(data);
    } catch (error) {
      alert("error");
    }
    setLoading(false);
  };

  return (
    <div className=" bg-zinc-950 h-screen flex justify-center items-center">
      <form onSubmit={onSubmit}>
        <input
          type="text"
          placeholder="Looking for a movie?"
          onChange={(e) => setPrompt(e.target.value)}
          className="p-2 block bg-neutral-700 text-white w-full rounded-md"
        />
        <button
          className="bg-emerald-500 p-2 rounded-md block mt-2 text-white disabled:opacity-50"
          disabled={!prompt || loading}
        >
          Generate
        </button>
        {result && typeof result === "string" && (
          <p className=" text-xl font-bold text-white max-w-xs my-10">
            {result}
          </p>
        )}
      </form>
    </div>
  );
}

from the console the error is located on const response = await fetch("/api/generate", {

What I expect the endpoint request to be done.

Upvotes: 0

Views: 86

Answers (1)

wongacj
wongacj

Reputation: 148

A 404 error means your backend is running, but the route is not found. In local development, like you are doing, there is a chance you don't have the route setup correctly. Have you considered your directory structure may be incorrect? The file api/generate/route.tsx should be under pages/api/generate/route.tsx.

Next.js has an official lesson with working sample code for a simple route that you could reference. That might give you an idea of what you are missing in your code.

Upvotes: 0

Related Questions