I am having a problem with sending form data through the API route
Answered
Alligator mississippiensis posted this in #help-forum
Alligator mississippiensisOP
I am using Mongoose to keep connected with database. I can see all my required datas coming in the Network tab. But I am getting an
Invalid Data ERROR.Answered by Toyger
const { chnl_id, chnl_name, chnl_desc, category, createdBy } = req.json() as unknown as TChannel;I think you need to
await your req.json iirc it return promise.12 Replies
Alligator mississippiensisOP
This is what my API route looks like:
import Channels from "@/models/Channels";
import connect from "@/utils/server-helper";
import { NextRequest, NextResponse } from "next/server";
type TChannel = {
chnl_id: string;
chnl_name: string;
chnl_desc: string;
category: string;
createdBy: string;
};
export async function POST(req: NextRequest, res: NextResponse) {
await connect();
const { chnl_id, chnl_name, chnl_desc, category, createdBy } = req.json() as unknown as TChannel;
const existing_channel = await Channels.findOne({chnl_id: chnl_id});
if (existing_channel) {
//if there is an existing channel with the same Channel ID
return NextResponse.json({ message: "Channel was already created" },{ status: 400 }); //throw a Next.js Response with an error
}
if (!chnl_id || !chnl_name || !chnl_desc || !category || !createdBy) {
return NextResponse.json({ message: "Invalid Data" }, { status: 422 });
}
const newChannel = new Channels({
chnl_id,
chnl_name,
chnl_desc,
category,
createdBy,
});
try {
await newChannel.save();
return NextResponse.json(
{ message: "Channel is created" },
{ status: 200 }
);
} catch (error) {
console.log(error);
return NextResponse.json({ message: "Server error" }, { status: 500 });
}
}This is my
page.tsx file:Alligator mississippiensisOP
as you can see I am getting the datas
@Alligator mississippiensis Click to see attachment
Alligator mississippiensisOP
getting this as a response
Alligator mississippiensisOP
I don't know what causes this issue.
Alligator mississippiensisOP
@Ray hi mate, could you help me about that? I would really appreciate it.
Toyger
const { chnl_id, chnl_name, chnl_desc, category, createdBy } = req.json() as unknown as TChannel;I think you need to
await your req.json iirc it return promise.Answer
Alligator mississippiensisOP
You are a life saver man. How come I didn't see that
Thanks @Toyger