'Backend is not running after post request

I am trying to create a stripe checkout project but was stuck when I found that the URL is changing after clicking my plan button but was not able to provide that button value to the backend. Here is my code for front-end where I am doing this :

import React, { useEffect, useRef } from "react";
import { isAuth } from "../helpers/auth";
import { useNavigate } from "react-router-dom";
import styles from "./Pricing.module.scss";
import ScriptTag from "react-script-tag";
import { loadStripe } from "@stripe/stripe-js";

const PUBLISHABLE_KEY =
  "pk_test_453765834";

export const Pricing = () => {
  const buttonValue = useRef();

  const navigate = useNavigate();

  const setBtnValue = (e) => {
    buttonValue.current = e.target.value;
  };
  const checkoutHandler = async (e) => {
    const btnValue = buttonValue.current;
    const stripe = await loadStripe(PUBLISHABLE_KEY);
    console.log(btnValue);
    fetch("http://localhost:5000/api/checkout", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        btnValue,
      }),
    })
      .then((result) => result.json())
      .then(({ sessionID }) => stripe.redirectToCheckout({ sessionID }))
      .then((result) => {
        console.log(result.error.message);
      });
  };
return (
<div>
  <ScriptTag
    isHydrating={true}
    type="text/javascript"
    src="https://js.stripe.com/v3/"
  />
<form onSubmit = {checkoutHandler}>
        <button
          value= 'price_bdsahfbadshb'
          type="submit"
          className="btn"
          name="product"
          onClick={setBtnValue}
        >
          Upgrade Now
        </button>
</div>
)
}

Here is my route in the backend for receiving this value :

router.post('/checkout' , async(req,res) => {
    const product = req.body;
    console.log(product);
    }

But in the above code, I am receiving this req.body as empty, and sometimes my backend run first then the front-end. Please check this problem anyone and guide me.



Solution 1:[1]

You should check your network tab and look for this post request there. Check the name value and see if it is same thing with the value name for the response. And also the buttonValue is the value name in the backend and you never assign it to receive the request body in the backend. Like this: buttonValue: req.body.buttonValue

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paulliano