Unable to populate database with data in Next Js via internal POST API

<div className={styles.Panier}>
     <p onClick={()=>Quantity>0?NewItem(data,Quantity):console.log("Quantity must be more 
     than 0")}>Add To Cart</p>
</div>

Upon clicking the above div, it triggers the NewItem function as shown below:

    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);
    };

The expected flow is for the request to go to the '/api/UpdateCart' API (which uses Prisma):

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;
    
    let newItem = await prisma.item.create({
        data: {
            ProductId: Id,
            Quantity: Qte,
            CartId: cartId
        }
    });
    return res.status(200).json(newItem);
}

An issue arises where accessing the endpoint through Postman works fine, but using the NewItem function mentioned earlier results in a 500 server error displayed like so:

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

Your assistance on resolving this issue would be greatly appreciated. Thank you for taking the time to help.

Answer №1

After a lengthy search, I finally discovered that the issue lay within the API code itself. Due to having one-to-many relationships, I needed to properly 'connect' the complete 'Cart' and 'Product' records in my item record.

1. Previous API Code:

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. Corrected 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);
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modify THREE.Mesh.position when slider value changes

Hey everyone, I've been tinkering with mesh translations using the Three.js library. I've set up HTML sliders to dynamically update the values within my project through JavaScript. Here's an example of what I'm working on: https://i.s ...

Conditionals causing issue with React Button disabled property functionality

Having a DIV with two child elements, namely buttons that should be disabled under certain conditions. Despite correct conditions being applied, the buttons remain enabled which is causing confusion. The code snippet in question is as below : < di ...

REST operations are malfunctioning while other methods are functioning correctly

It's quite strange, but I'm clueless about what could be causing this chaos. Here's the code snippet I'm working with: var express = require('express'); var router = express.Router(); var mongoose = require('mongoose&ap ...

The dynamic relationship between redux and useEffect

I encountered a challenge while working on a function that loads data into a component artificially, recreating a page display based on the uploaded data. The issue arises with the timing of useEffect execution in the code provided below: const funcA = (p ...

Incorporating external API information into Google Maps

My current challenge involves creating a polygon on Google Maps using data obtained from an external API found at . Upon analyzing the API response, the following information is provided: { "id": 28, "name": "Local spots", "description": "", "isprivate": ...

Tips for using NextJS with Static Site Generation (SSG) and Server-Side Rendering (SSR

I recently built a NextJS site that is statically generated during the build process (SSG). There are two key features I am looking to add next: Google Analytics integration Implementation of GDPR compliant opt-in cookie options While setting up Google ...

Discover the final index of an array with Angular's ng-repeat functionality

I'm currently working with an Object that contains array values which I am trying to iterate over. Here's a simplified example of what I have: $scope.messages = { "1": [ { "content": "Hello" }, { "content": "How are you" }, { "conte ...

Add a span tag with the class "javascript" around the index of a character within a string

Within an element, I have a string as such: <p>I like trains and planes</p> Using jQuery's .text(), I extract the text and store it in a variable. var str = $('p').text(); I aim to identify a specific character, let's sa ...

Exploring the world of web development with a mix of

var articles = [ {% for article in article_list %} {% if not forloop.first %},{% endif %} { title: "{{ article.title }}", slug: "{{ article.slug }}", content: "{{ article.content }}", auth ...

Tips for ensuring the border matches the size of the image

I am in the process of creating a website that includes a filter option. My plan is to have the filters displayed on the left side and the items on the right side. To achieve this layout, I have implemented a scrollable div for the items. However, I notic ...

Issues encountered while optimizing JSON file in a ReactJS program

I'm struggling with utilizing Array.prototype.map() in Javascript Specifically, I'm reformatting a JSON file within my react app, which looks like: { "id": 1, "title": "Manage data in Docker", "description": "How to use v ...

Ensure to add the name attribute when the checkbox is selected

Can anyone assist me with this issue? I am trying to create a form where, upon checking a checkbox, a name attribute should be added to the input field of the checkbox along with a number at the end. My current implementation is not working as expected. ...

Use leaflet.js in next js to conceal the remainder of the map surrounding the country

I'm currently facing an issue and would appreciate some assistance. My objective is to display only the map of Cameroon while hiding the other maps. I am utilizing Leaflet in conjunction with Next.js to showcase the map. I came across a helpful page R ...

I am experiencing issues with the functionality of front-page.php on my WordPress website

Seeking guidance in addressing a web development issue: I have encountered a problem with a website that I am currently working on locally using WordPress. I added the following code to the header.php file: <link rel="stylesheet" type="text/css" href= ...

Is it possible to generate an HTML element by utilizing an array of coordinates?

I have a set of 4 x/y coordinates that looks like this: [{x: 10, y: 5}, {x:10, y:15}, {x:20, y:10}, {x:20, y:20}] Is there a way to create an HTML element where each corner matches one of the coordinates in the array? I am aware that this can be done usi ...

Getting WordPress post author information using React.js: a step-by-step guide

Whenever I attempt to retrieve the users of my WordPress site using this method: https://sitename/wp-json/wp/v2/users Unfortunately, it results in an error message that reads: <title> 403 Forbidden </title> Is there a different way to acc ...

Add CSS styles to the outermost container element when the slideshow is currently in use

On my homepage, I have a carousel featuring multiple slides. However, when the third slide appears in the carousel, the positioning of the carousel buttons within the div class="rotator-controls" shifts downward due to the space taken up by the image. My o ...

Exporting Data and Utilizing a Steady Data Table

I have incorporated the Fixed Data Grid into my latest project. https://facebook.github.io/fixed-data-table/example-sort.html My goal is to generate csv and pdf reports from the data displayed on the grid. Could you please advise me on how to export gri ...

Effortlessly switch between multiple divs with jQuery

I am working on a functionality where multiple divs should be displayed or hidden based on the button clicked. Initially, all buttons and divs are visible. Upon clicking a button, only the corresponding div should be visible. Subsequent clicks on other but ...

Designing a fixed bottom footer enclosed within a wrapper that expands from the top header to the bottom footer

I have created the basic structure of my webpage using HTML / CSS. However, I now realize that I need a sticky footer that remains at the bottom of the screen with a fixed position. Additionally, I want the main content area, known as the "wrapper," to str ...