简体   繁体   中英

Unable to make post request to server : 404 error

I am trying to send data to my server but I think I am not sending it correctly.

I get the following error in the backend

Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>), here is my front call with fetch:
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js"
import * as styles from './Checkout.module.scss'
export default function Checkout({ setCheckout, currentPackage }) {

    const stripe = useStripe();
    const elements = useElements();

    const pay = async () => {
        try {
            const response = await fetch("http://localhost:5001/api/user/pay/coins", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: {
                    "userId": '61b1bfe057e557000845fc78',
                    "coins": currentPackage
                }
            }
            );
            const data = await response.json();
            const cardElement = elements.getElement(CardElement);
            const confirmPayment = await stripe.confirmCardPayment(
                data.clientSecret,
                { payment_method: { card: cardElement } }
            );
            const { paymentIntent } = confirmPayment;
            if (paymentIntent.status === "succeeded") alert(`Payment successful!`);
            else alert(`Payment failed!`);
        } catch (err) {
            alert("There was an error in payment:", err);
        }
    };
    return (
        <div className={styles.modal_container}>
            <div className={styles.modal_box}>
                <div className={styles.modal_header}>
                    <p className={styles.modal_title}>Payment</p>
                    </svg>
                </div>

                <div className={styles.modal_body}>
                    <div className={styles.card}>
                        <CardElement />
                        <button onClick={() => pay()}>Buy</button>
                    </div>
                </div>
            </div>
        </div>
    )
}

And this is my back that shows the message I told you about that is running on Express

const router = require("express").Router();
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const User = require("../models/User");

router.post("/coins/", async (req, res) => {

    const userId = req.body.userId;
    const coins = req.body.coins;

    var amount;

    switch (coins) {
        case 1000:
            amount = amount + 9999;
            break;
        case 5000:
            amount = amount + 29999;
            break;
    }
    try {

        const paymentIntent = await stripe.paymentIntents.create({
            amount,
            currency: "usd",
            payment_method_types: ["card"],
            metadata: {
                name: "value",
            },
        });
        const clientSecret = paymentIntent.client_secret;

        await User.findOneAndUpdate({ _id: userId }, { $inc: { coins: coins } });

        res.json({ clientSecret, message: "Payment Initiated" });
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: "Internal server error" });
    }
});

module.exports = router;

Kindly help me rectify the mistakes.

As explained here , you should stringify your request body payload on the client-side:

const response = await fetch("http://localhost:5001/api/user/pay/coins", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    "userId": '61b1bfe057e557000845fc78',
                    "coins": currentPackage
                })
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM