Next.js Discord

Discord Forum

API not working in next project:

Answered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
Below is my open api:

// pages/api/gevs/constituency/[constituency].js

import { connectMongoDB } from "@/lib/mongodb";
import Candidate from "@/models/candidate";

export async function GET(req) {
    try {
        await connectMongoDB();

        // Retrieve the constituency from the URL
        const constituency = req.nextUrl.pathname.split("/").pop();

        // Fetch candidates from the database
        const candidates = await Candidate.find({ constituency }).sort({ votes: -1 });

        // Check if candidates are found
        if (!candidates || candidates.length === 0) {
            return new Response(
                JSON.stringify({ message: "No candidates found in this constituency" }),
                { status: 404, headers: { "Content-Type": "application/json" } }
            );
        }

        // Format the response
        const response = {
            constituency: constituency,
            result: candidates.map(candidate => ({
                name: candidate.name,
                party: candidate.party,
                vote: candidate.votes
            }))
        };

        return new Response(
            JSON.stringify(response),
            { status: 200, headers: { "Content-Type": "application/json" } }
        );
    } catch (error) {
        console.error("Error fetching constituency data: ", error);
        return new Response(
            JSON.stringify({
                message: "An error occurred while fetching constituency data",
                error: error.message,
            }),
            { status: 500, headers: { "Content-Type": "application/json" } }
        );
    }
}


It is stored in as app/api/gevs/constituency/[constituency].js

It returns a 404 not found every time. Any advice?
Answered by Ray
// app/api/gevs/constituency/[constituency]/route.js
export async function GET(req) {
    return new Response(
        JSON.stringify({ message: "Test response" }),
        { status: 200, headers: { "Content-Type": "application/json" } }
    );
}
View full answer

29 Replies

Polar bearOP
I have tried using a simple request such as:

export async function GET(req) {
    return new Response(
        JSON.stringify({ message: "Test response" }),
        { status: 200, headers: { "Content-Type": "application/json" } }
    );
}


And this too returns 404 not found
i tried the version u just sent *
@Ray http://localhost:3000/api/gevs/constituency/northern-kunlun-mountain
Polar bearOP
this also returns 404 This page could not be found.
It is stored in as app/api/gevs/constituency/[constituency].js
so its app folder
Polar bearOP
yes
ignore the pages comment
@Polar bear yes
// app/api/gevs/constituency/[constituency]/route.js
export async function GET(req) {
    return new Response(
        JSON.stringify({ message: "Test response" }),
        { status: 200, headers: { "Content-Type": "application/json" } }
    );
}
Answer
create it with the path
app/api/gevs/constituency/[constituency]/route.js
@Ray app/api/gevs/constituency/[constituency]/route.js
Polar bearOP
ah this works ty
one more q
the specification wants the following url
GET /gevs/constituency/northern-kunlun-mountain
is there any way i can do this without the api folder?
do i just move it all outside the api folder?
@Polar bear do i just move it all outside the api folder?
yes just create the route at app/gevs/constituency/[constituency]/route.js
appreciated
<33
no prob