0

I have a react app where I am trying to create an axios post request, and the parameters doesn't seem to work. Strange part is I have other axios post calls in other components and they work just fine, it is just this component here that is not working right.

My backend is golang based, and everything is working well, tested on postman so I'm sure it's the frontend parameters that are causing the issue. For reference, here is the postman test: enter image description here

Let me point out the part where I think the error is coming from:

let param = JSON.stringify({ userrefer: JSON.stringify(userID), productrefer: JSON.stringify(itemID), quantity: JSON.stringify(order[itemID]) })

At first, I did not have the JSON.stringify portion, it was simply

let param = { userrefer: userID, productrefer: itemID, quantity: order[itemID] }

but it didn't work, and I thought I went wrong with my syntax somewhere, so I spent a great amount of time editing and trying all sorts of combinations of the syntax but it didn't help. After some searching online I then found a recommendation to serialise it hence I added the JSON stringify but to no avail.

The response I get back is always 400, no matter what I do. Here is a screenshot. enter image description here

This is the whole code for the particular component where I'm having trouble:

import React from 'react';
import Card from './Card';
import axios from "axios";
import { useEffect } from 'react';
import { useState } from 'react';

function Products({ isLoggedIn, userID }) {
    const [instruments, setInstruments] = useState([]);
    const [order, setOrder] = useState({});

    const handleOrderChange = (event, itemID) => {
        const value = event.target.value;
        setOrder({ ...order, [itemID]: value });
    };

    useEffect(() => {
        async function getInstruments() {
            await axios
                .get(
                    `http://127.0.0.1:3000/api/products`
                )
                .then((res) => {
                    setInstruments(res.data.message)

                })
        }
        getInstruments()
    }, [])

    const handleBuy = async (event, itemID, qty) => {

        event.preventDefault();

        if (order[itemID] > qty) {
            alert(`You cannot buy more than the quantity of ${qty}!`)
        }
        else if (order[itemID] <= 0) {
            alert(`You cannot buy 0 or less instruments...`)
        }
        else {
            let param = JSON.stringify({ userrefer: JSON.stringify(userID), productrefer: JSON.stringify(itemID), quantity: JSON.stringify(order[itemID]) })
            console.log(param)
            await axios
                .post(
                    `http://127.0.0.1:3000/api/orders`, param
                )
                .then((res) => {
                    console.log(res)

                })
                .catch((err) => {
                    console.log("err", err);
                });
        }
    };


    return (

        isLoggedIn === true ? (<div>
            <h1>
                Products
            </h1>
            <h4>
                Here are the musical products for sale.
            </h4>

            {instruments.map((element) => {
                return (
                    <>
                        <Card name={element.name} img={element.img} price={element.price} qty={element.qty} description={element.description} />
                        <input type="number" id="qty" name="qty"
                            onChange={(e) => handleOrderChange(e, element.id)}
                            min="0"
                            max={element.qty} />
                        <button onClick={(e) => handleBuy(e, element.id, element.qty)}>Buy</button>
                    </>
                )
            })}
        </div>) : (<div>
            <h1>
                Products
            </h1>
            <h4>
                Here are the musical products for sale.
            </h4>

            {instruments.map((element) => {
                return (
                    <>
                        <Card name={element.name} img={element.img} price={element.price} qty={element.qty} description={element.description} />
                    </>
                )
            })}
        </div>)



    )
}

export default Products

For my other components where axios post works, I used react useState to pass in the parameters. I am not sure whether it's because I'm not using useState for this component's input paramters for axios, that's why this is an issue. Appreciate any guidance/tips!

MatCode
  • 114
  • 4
  • 14

2 Answers2

2

First of all, try to look at network tab and see there what you are actually sent.

Then, if you use JSON.stringify, there is no need to do it for each property.

let param = JSON.stringify({ userrefer: JSON.stringify(userID), productrefer: JSON.stringify(itemID), quantity: JSON.stringify(order[itemID]) })
          

Just do

let param = JSON.stringify({ userrefer: userID, productrefer: itemID, quantity: order[itemID] })
          

If you try to stringify const test = 8 twice, you will get '"8"' as a result which might cause errors. JSON.stringify is working deeply, not just with first layer of object or etc.

Actually I'm not sure that you need here JSON.stringify at all. Try running without it, and take a loot at network tab.

Provide screens from network tab, so I can figure out whats happening

  • Here is the [screenshot](https://imgur.com/a/curuNRu) - I think I know why, the request is not in JSON format even after JSON.stringify – MatCode Nov 03 '22 at 08:55
-1

After trying out Oleg's answer, I managed to parse in JSON rather than a form data. However, I still get user doesn't exist. enter image description here enter image description here

In contrast, when I test the exact same input parameters with postman, it works. I am very confused, and at this point I'm not sure whether it's my backend that is having an issue or the frontend. enter image description here

MatCode
  • 114
  • 4
  • 14