trayng to create data using nextjs and prisma sqlite
Unanswered
DeFc0n posted this in #help-forum
DeFc0nOP
a
111 Replies
DeFc0nOP
here is my handler
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../prisma/client";
export default async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method !== "POST") {
return res.status(405).json({ message: "method not allowed" });
}
const transData = JSON.parse(req.body);
const saveData = await prisma.transaction.create({
data: transData,
});
res.json(saveData);
};Plott Hound
what version of next are you using?
DeFc0nOP
latest
Plott Hound
app router?
DeFc0nOP
yes
Plott Hound
this is wrong:
read the docs for proper syntax: https://nextjs.org/docs/app/building-your-application/routing/route-handlers
eg
export default async (req: NextApiRequest, res: NextApiResponse) => {read the docs for proper syntax: https://nextjs.org/docs/app/building-your-application/routing/route-handlers
eg
export async function POST() {Plott Hound
your code is from older version of next
if you still have problems share your error logs
DeFc0nOP
there are no error logs the data in trayng to create dosnt create
Plott Hound
yeah you need to add console logs to your route handler to actually see what errors are happening.
i just added some to your non working code as an example:
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../prisma/client";
export default async (req: NextApiRequest, res: NextApiResponse) => {
console.log("Request received", req.method);
if (req.method !== "POST") {
console.log("Non-POST method received");
return res.status(405).json({ message: "method not allowed" });
}
console.log("Request body:", req.body);
const transData = JSON.parse(req.body);
console.log("Parsed transaction data:", transData);
try {
const saveData = await prisma.transaction.create({
data: transData,
});
console.log("Data saved successfully:", saveData);
res.json(saveData);
} catch (error) {
console.error("Error saving data:", error);
res.status(500).json({ message: "Internal server error" });
}
};your code should look something like this in next14:
// app/api/your-route-name/route.ts
import prisma from "../../prisma/client";
export async function POST(req: Request) {
const transData = await req.json();
const saveData = await prisma.transaction.create({
data: transData,
});
return new Response(JSON.stringify(saveData), {
headers: {
'Content-Type': 'application/json',
},
});
}DeFc0nOP
OHHHH
thank you
and make sure to protect that route to minimise access for other users 🙂
DeFc0nOP
im using clerk the entire project is locked with login,
Plott Hound
yeah exactly what Risky said. Also while its fine to use api routes/ route handlers, in Next14 we are encouranged to use Server Actions. so check the docs for those. it would be more applicable to your code
remember console logs are your friend. its the fastest way to figure out why something isnt working
@Plott Hound remember console logs are your friend. its the fastest way to figure out why something isnt working
DeFc0nOP
i added a bunch none of them send anythink, i think i have coded the table wrong
Plott Hound
share the front end code that is trying to access this api route pls
@DeFc0n Click to see attachment
DeFc0nOP
its this one, without console logs though
Plott Hound
remember in the route handler the logs will show up in the server console (vscode) not in the browser since its happening on the server
DeFc0nOP
yes i know, nothing shows up
@DeFc0n yes i know, nothing shows up
Plott Hound
going back to work now, but i'd add a bunch of logging to your front end and see why its failing. you could even just paste it in chatGPT and say add a bunch of console logs to this
@DeFc0n alright thank you
how are you accesing the routes?
DeFc0nOP
const handleSubmit = async (e) => {
console.log("handleSubmit");
e.preventDefault();
console.log("Submitting formData:", formData);
try {
const response = await fetch("/api/transactions", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
});
if (!response.ok) {
throw new Error(response.statusText);
}
const result = await response.json();
console.log("Transaction created:", result);
// Clear the form
setFormData({
type: "",
amount: "",
description: "",
});
console.log("Cleared formData:", formData);
} catch (error) {
console.error("Error saving transaction:", error);
}
};have you tried accesing your route via postman/curl/rest
DeFc0nOP
i have not, let install postman,
just do this
hmm that might be hard to insert JSON object
@DeFc0n jsx
const handleSubmit = async (e) => {
console.log("handleSubmit");
e.preventDefault();
console.log("Submitting formData:", formData);
try {
const response = await fetch("/api/transactions", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
});
if (!response.ok) {
throw new Error(response.statusText);
}
const result = await response.json();
console.log("Transaction created:", result);
// Clear the form
setFormData({
type: "",
amount: "",
description: "",
});
console.log("Cleared formData:", formData);
} catch (error) {
console.error("Error saving transaction:", error);
}
};
open Network tabs,
click on the button on the browser,
and see if any new request are made
click on the button on the browser,
and see if any new request are made
DeFc0nOP
not sure but i think its not reaching the api
yes
so i think its the problem with handleSubmit
DeFc0nOP
the logs agree
when i click the button no logs show
then how you did you set up handleSubmit on the buttons :v
DeFc0nOP
<form onSubmit={handleSubmit}>
<button
onSubmit={handleSubmit}
type="submit"
className="text-blue-500"
>
Submit
</button>
onSubmit={handleSubmit}
type="submit"
className="text-blue-500"
>
Submit
</button>
none of them work,
does the
console.log("handleSubmit"); workpostman returns error 404 not found
send client side code
of how you setup the <form>
DeFc0nOP
weird af
any console messages on the browser?
DeFc0nOP
nope
should i re install node modules
hmmm
try making a new form
a simple form on your project
and focus on handleSubmit, <form> and <button>
DeFc0nOP
ok
@aardani and focus on handleSubmit, <form> and <button>
DeFc0nOP
i comented out everythink apart these, still nothing
this is very odd
very odd indeed
are you running on
npm run dev and not npm run start?DeFc0nOP
yes npm run dev
try using onClick instead of onSubmit for buttons
and try using action instead of onSubmit for form
(try one at a time)
yeah do what alfon said 🙂
@aardani try using onClick instead of onSubmit for buttons
DeFc0nOP
this did nothing
@aardani and try using action instead of onSubmit for form
DeFc0nOP
this though, nothing happens, even the form does not clear
@DeFc0n haha, no problem
yeah i saw npm run dev and one just before was doing vercel dev vs npm dev, sorry again
ok
try creating a new project 😠and create form in there
DeFc0nOP
very odd indeed
i dont even know how you got it this far ngl ðŸ«
yeahh
DeFc0nOP
first time doing a project in windows
not suprising if windows messed up lol
shouldnt be that hard
just npm run dev and open in browser :/
DeFc0nOP
easier in linux
lazy to do a whole new rice with arch
DeFc0nOP
@aardani i found out what i did wrong
what did you do wrong
DeFc0nOP
in api i had api/transactions.js not /api/transactions/route.js
i hope this is the biggest facepalm ive ever seen
but did it fix the issue?
.......................
DeFc0nOP
i know im stupid
no
stop saying you are stupid people, ive seen that twice
LETSSSSSSSSSS GOOOOOOOOOOOOOOOOOOOO
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
i can now create data,
using postman
Plott Hound
haha had to come back and see how you got on. glad you figured it out XD
@Plott Hound haha had to come back and see how you got on. glad you figured it out XD
DeFc0nOP
ha ye, thanks now i just need to add the UI
Plott Hound
whenever i make a route handler i visit the physical url of it to make sure it responds, good practice
im getting more odd bugs and stuff aparatly my code is good but it dosnt work