The issue encountered during a POST request in Postman is a SyntaxError where a number is missing after the minus sign in a JSON object at position 1 (line 1

Running my API in a website application works flawlessly, but encountering SyntaxError when testing it in Postman - specifically "No number after minus sign in JSON at position 1" (line 1 column 2). The data is correctly inputted into the body of Postman and the names are accurate, yet the error persists. Strangely enough, this issue only occurs with POST requests; GET and DELETE requests function properly in Postman. The JSON response post adding a product to the basket from the website reads as follows:

{ id: 70, productId: 21, userId: 10, size: 'Medium', customerQuantity: 1 }

However, when attempting to replicate the process in Postman by providing the necessary data in the body, the error mentioned in the title arises.

The API code:

import prisma from "@/app/prismadb";
import { NextResponse } from "next/server";

export async function POST(request: Request) {
    const body = await request.json();
    const { productId, userId, size, customerQuantity } = body;

   

    try {
        const existingCartItem = await prisma.basket.findFirst({
            where: {
                productId,
                userId,
                size: {
                    contains: size, 
                }
            },
        });

        if (existingCartItem) {
            await prisma.basket.delete({
                where: {
                    id: existingCartItem.id,
                },
            });
        }

        const product = await prisma.basket.create({
            data: {
                productId,
                userId,
                size,
                customerQuantity
            },
        });

        return NextResponse.json(product);
    } catch (error) {
        console.log("Error adding product to cart", error);
        return NextResponse.error();
    }
}

export async function DELETE(request: Request) {
    const body = await request.json();
    const { productId, userId } = body;

    try {
        const deleteItem = await prisma.basket.deleteMany({
            where: {
                productId: productId,
                userId: userId,
            },
        });

        return NextResponse.json(deleteItem);
    } catch (error) {
        console.log("Error deleting product", error);
        return NextResponse.error();
    }
}



Answer №1

If you are inputting data into the postman body and referring to it as a "JSON response", you may encounter an error because it is not valid JSON but rather a JavaScript object.

To fix this, make sure your code looks like this:

{ "id": 70, "productId": 21, "userId": 10, "size": 'Medium', "customerQuantity": 1 }

Answer №2

I discovered a simple error in my approach: the API required JSON data in the request body rather than form-data, which I was submitting via Postman. By switching to raw mode instead of form-data and specifying JSON from the dropdown menu, I successfully resolved the issue.

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

Converting a string to JSON format with JavaScript

My string is structured in JSON format like this: "{""c1"": ""value1"", ""c2"": ""value2""}" After storing it in an SQLITE database, I use the following Javascript code to retrieve it back as JSON: var req= "SELECT json_column from my_table"; var re ...

Exploring the capabilities of UIGrid in conjunction with TypeScript DefinitelyTyped has been a

I've noticed that the latest release of UI Grid (RC3) has undergone significant architectural changes compared to nggrid. I am encountering some problems with the definitelytyped files for nggrid because they are from a different version. Will there ...

variety of provider setups available in Angular

Trying to learn Angular from various online sources can be quite confusing, as different people use different patterns when writing functions. Can someone please explain the .provider concept in Angular? I have experimented with the .provider method using ...

Maximizing the potential of typescript generics in Reactjs functional components

I have a component within my react project that looks like this: import "./styles.css"; type InputType = "input" | "textarea"; interface ContainerProps { name: string; placeholder: string; as: InputType; } const Conta ...

incomplete constructor for a generic class

I have multiple classes that I would like to initialize using the following syntax: class A { b: number = 1 constructor(initializer?: Partial<A>) { Object.assign(this, initializer) } } new A({b: 2}) It seems to me that this ini ...

Implement the map function to validate every input and generate a border around inputs that are deemed invalid or empty upon button click

Currently, I'm in the process of developing a form with multiple steps. At each step, when the next button is clicked, I need to validate the active step page using the map function. My goal is to utilize the map function to validate every input and ...

An error occured when attempting to read the 'status' property of an undefined value in node.js, express.js, and mysql

I recently started working with node.js and encountered a challenge in fetching data from mysql and sending it to an API response. Below is my setup: db.js: var mysql = require('mysql2'); var util = require('util') const pool = mysql ...

Guide to specifying an explicit return type annotation for a recursive closure with JSDoc

In a project that utilizes vanilla JavaScript and type checking with tsc through JSDoc annotations, I have encountered a challenging use case. There is a function that returns another function, which may recursively call itself while also reassigning certa ...

Are you looking for a way to prevent the default behavior of an event in angular-ui-router 1.0.x? Check out

Recently, I made a change in my code where I replaced $stateChangeStart with $transitions.onStart $rootScope.$on('$stateChangeStart', function(e, ...){ e.preventDefault(); // other code goes here... }); Now, the updated code looks lik ...

Trouble with displaying days on the Datepicker

I'm currently facing an issue with my datepicker. I have a specific set of days that should be highlighted on the calendar, and it needs to be constantly updated. For example, past days are removed from the calendar automatically to keep it current. H ...

Using AngularJS variables within JavaScript code

This is my introduction to using AngularJS. The code snippet below displays the desired output: <a href="http://www.example.com/xyz/{{life.animal}}/" target="_blank">Hello </a> Upon clicking, it redirects to: http://www.example.com/xyz/c ...

Display text on the screen with a customized design using JavaScript's CSS styles

I need help with printing a specific page that contains some information designed in print.css. I want to print this page, including an image, with the same style. function printContent() { var divContents = document.getElementById("terms").innerH ...

Exploring the Difference Between $onChanges and $onInit in Angular Components

What sets apart the use of Controller1 compared to Controller2? angular.module('app', []) .component('foo', { templateUrl: 'foo.html', bindings: { user: '<', }, controller: Controller1, ...

Why is my Next.js <Image> tag displaying JPG instead of Webp or Avif formats?

When using Nextjs, I anticipated seeing the Image component rendered as .WebP or .AVIF format, but it continues to display jpg instead - Here is my next.config.js file: /** @type {import('next').NextConfig} */ module.exports = { images: { ...

Is a Selenium loop a viable option?

</head> <body> <table cellpadding="1" cellspacing="1" border="1"> <thead> <tr><td rowspan="1" colspan="3">test</td></tr> </thead><tbody> <tr> <td>click& ...

What is the correct way to set a function as the value for an object without using quotation marks?

I am facing a challenge of generating very large JavaScript files using Node.js. Each file contains a const variable that holds values tailored for the specific file, with these values only known at runtime. For example: 'use strict' const lib ...

Unlocking the secret path to reach an untraceable object nested within another object using

After using php's json_encode() function, I received a string that looks like this: [ { "key1":"value1", "key2":"value2", "key3":"value3" }, { "key1":"value1", "key2":"value2", "key3":"value3" } ] To convert the string into a J ...

What could be the reason for an async function to send an empty object in the request body?

I'm currently utilizing nuxt.js, mongoDB, express, and bodyParser as well Unfortunately, the solutions provided by others do not solve my issue, as having bodyParser does not seem to fix it. The uploadPet function is designed to collect form data an ...

Executing multiple child processes in a loop with asynchronous operations and collecting the output after the loop concludes

Here's a snippet of code I've been working on... const { exec } = require('child_process'); const Main = async () => { const result = await RetrieveAllItems(); console.log('output', result); }; const RetrieveAllI ...

Extracting the content within Angular component tags

I'm looking for a way to extract the content from within my component call. Is there a method to achieve this? <my-component>get what is here inside in my-component</my-component> <my-select [list]="LMObjects" [multiple]=&qu ...