Next.js Discord

Discord Forum

api routes not working

Answered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
import mongoose from "mongoose";
import { NextRequest, NextResponse } from "next/server";
import { v4 as uuidv4 } from "uuid";

const { MONGODB_URI } = process.env;

if (!MONGODB_URI) {
  throw new Error(
    "Please define the MONGODB_URI environment variable inside .env.local"
  );
}

if (mongoose.connections[0].readyState) {
  console.log("Already connected.");
} else {
  mongoose.connect(MONGODB_URI).catch((err) => console.log(err));
}

const fileSchema = new mongoose.Schema({
  _id: {
    type: String,
    default: uuidv4,
  },
  content: String,
});

const File = mongoose.models.File || mongoose.model("File", fileSchema);

export async function POST(request: Request) {
  const body = await request.json();
  const file = new File({ content: body.content });
  await file.save();
  return NextResponse.json({ slug: file.id });
}

export async function GET(request: NextRequest) {
  const slug = request.nextUrl.pathname.split("/").pop();
  if (!slug || slug === "files") {
    const files = await File.find();
    const allSlugs = files.map((file) => ({ slug: file._id }));
    return NextResponse.json({ allSlugs });
  } else {
    // const file = await File.findById(slug);
    return NextResponse.json({ asd: "asd" });
  }
}


the /api/files/{uuid} path still returns a 404 error for some reason
Answered by Polar bear
i just switched to the pages router bc this took forever
View full answer

3 Replies

Polar bearOP
i just switched to the pages router bc this took forever
Answer
Polar bearOP
much more familiar w that
and it works now