简体   繁体   中英

Passing data to express backend

I'm adding a stripe checkout to my website with this code in my react front end

    const response = await fetch('/create-checkout-session', {
       method: 'POST',
       });

    const session = await response.json();

    // When the customer clicks on the button, redirect them to Checkout.
    const result = await stripe.redirectToCheckout({
      sessionId: session.id,
    });

and this one on my express server :

app.post("/create-checkout-session", async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    shipping_address_collection: {
      allowed_countries: ["BE", "FR", "DE", "CH"],
    },
    payment_method_types: ["card"],
    line_items: [
      {
        price_data: {
          currency: "usd",
          product_data: {
            name: "T-shirt",
          },
          unit_amount: 10 * 100,
        },
        description: "Product 1",
        quantity: 1,
      },
      {
        price_data: {
          currency: "usd",
          product_data: {
            name: "Tsklip",
          },
          unit_amount: 2000,
        },
        description: "Product 2",
        quantity: 2,
      },
    ],
    mode: "payment",
    success_url: "https://localhost:3000",
    cancel_url: "https://localhost:3000/cart",
  });

  res.json({ id: session.id });
});

I'd like to pass from my frontend to my backend some info. How could I do that ? Is it possible with this code ? Thanks !

You can pass data to body, then you can access them in express from req.body

const response = await fetch('/create-checkout-session', {
   method: 'POST',
   body: JSON.stringify({ info: 'my info message', id: 1})
});

Also you should use body-parser middleware to parse incoming request body

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