The Axios post method in my code is not functioning properly, leading to an ERR_BAD_REQUEST error in the console. I am unsure of where the issue lies. The tutorial Im Following has the coder saying it works for him, but not for me. We have the same code because I have checked it multiple times!
const onSubmit = async (values: z.infer<typeof formSchema>) => {
try {
setLoading(true);
const response = await axios.post('/api/stores', values);
console.log(response.data)
} catch (error: any) {
console.error(error);
} finally {
setLoading(false);
}
};
api/stores/route.ts
import prismadb from "@/lib/prismadb";
import { auth } from "@clerk/nextjs";
import { NextResponse } from "next/server";
export async function POST(req: Request) {
try {
const { userId } = auth();
const body = req.json();
const { name }: any = body;
if (!userId) {
return new NextResponse("Unauthorized", { status: 401 });
}
if (!name) {
return new NextResponse("Name is required", { status: 400 });
}
const store = await prismadb.store.create({
data: {
name,
userId
},
});
return NextResponse.json(store);
} catch(error) {
console.log('[STORES_POST]', error);
return new NextResponse("Internal error", { status: 500 });
}
};
Due to my confusion, I haven't tried anything.
As confirmed with the poster through comments, the below code change resolved the issue. Just wanna wrap up the solution and share it here for more folks who may have the same issue in the future.
You should make sure the Axios
request is properly formatted and sending JSON
. So, in the onSubmit()
function, update the axios
code block with the below:
const response = await axios.post('/api/stores', JSON.stringify(values), {
headers: {
'Content-Type': 'application/json'
}
});