<div className={styles.Panier}>
<p onClick={()=>Quantity>0?NewItem(data,Quantity):console.log("Quantity must be more
than 0")}>Add To Cart</p>
</div>
When Clicking on the that div the following NewItem
function gets executed:
let NewItem = async (data,Qte) => {
const response = await fetch('/api/UpdateCart',{
method: "POST",
body: JSON.stringify(
{
Qte,
data,
cartId: Cookies.get('cart')
}
),
headers:{
'Content-Type': 'application/json; charset=utf8'
},
});
console.log(response);
};
This normally should go to the api in '/api/UpdateCart' (I'm using prisma btw):
import { PrismaClient } from "@prisma/client";
export default async function handler(req, res)
{
let prisma = new PrismaClient();
let Id = req.body.Id;
let Qte = req.body.Qte;
let cartId = req.body.cartId;
//Creates the new item and adds it to the cart
let newItem = await prisma.item.create({
data: {
ProductId: Id,
Quantity: Qte,
CartId: cartId
}
});
return res.status(200).json(newItem);
}
Now the problem is that when i try the endpoint in postman it works like a charm, but when i use access it from the NewItem
function that i mentionned before, I get a 500 server error in the following way:
POST http://localhost:3000/api/UpdateCart 500 (Internal Server Error)
Response {type: 'basic', url: 'http://localhost:3000/api/UpdateCart', redirected: false, status: 500, ok: false, …}
body
:
(...)
bodyUsed
:
false
headers
:
Headers {}
ok
:
false
redirected
:
false
status
:
500
statusText
:
"Internal Server Error"
type
:
"basic"
url
:
"http://localhost:3000/api/UpdateCart"
[[Prototype]]
:
Response
I hope that u can help me and thank you for your time
CodePudding user response:
After more than a day of searching i found out that the problem was actually in API code since i was having one-to-many relationships I was supposed to 'connect' the full 'Cart' and 'Product' records into my item record.
1. This is the API code before the solution:
import { PrismaClient } from "@prisma/client";
export default async function handler(req, res)
{
let prisma = new PrismaClient();
let Id = req.body.Id;
let Qte = req.body.Qte;
let cartId = req.body.cartId;
//Creates the new item and adds it to the cart
let newItem = await prisma.item.create({
data: {
ProductId: Id,
Quantity: Qte,
CartId: cartId
}
});
return res.status(200).json(newItem);
}
2. This is the Correct API code:
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export default async (req, res) => {
let PrId = req.body.prodId;
let Qte = req.body.Qte;
let newItem = await prisma.item.create({
data:{
Quantity: Qte,
Product:{
connect:{
Id: PrId,
},
},
Cart:{
connect:{
Id: req.body.cartId
}
}
},
});
return res.status(200).json(newItem);
};