繁体   English   中英

无法向服务器发出 post 请求:404 错误

[英]Unable to make post request to server : 404 error

我正在尝试将数据发送到我的server ,但我认为我没有正确发送它。

我在后端收到以下错误

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

这是我的背影,上面显示了我告诉你的关于 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;

请帮助我纠正错误。

正如这里所解释的,您应该在客户端对您的请求正文有效负载进行stringify

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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