簡體   English   中英

在 node.js 中正確使用全局變量,或者有更好的方法嗎?

[英]Using global variables properly in node.js or is there a better way of doing this?

我正在嘗試從我的checkout.html文件(如下)中獲取用戶輸入的金額,以便我可以在server.js節點服務器上的 Stripe 代碼中使用它。

我無法從表單中獲取amount field ,因此我禁用了它並正在使用 console.log 和變量。 我試圖讓它與傳遞值的全局變量一起工作。

這兩個文件來自 Stripe 網站上的示例(您 select ' node ' 和 ' html ' 從頁面中,然后單擊 ' prebuilt ' 也)

https://stripe.com/docs/checkout/integration-builder

我的更改(抱歉,var 分配編號都是隨機的,用於測試)

**server.js** 

( lines 8-9 )
var test = 2242;
// console.log( amountglobal);


( line 22 )
unit_amount: test, 


**checkout.html** (line 47 )

amountglobal = 67865555;

我的問題是,如果我取消注釋第 9 行(目的是嘗試在第 22 行中使用amountglobal全局變量)然后由於某種原因服務器不會啟動,說amountglobal沒有定義......所以我可能有全局變量錯誤在結帳.html,它的

amountglobal = 67865555;

...也許首先有更好的方法來做到這一點,我知道全局變量通常不是理想的。

這里的最終結果是形成一個支付表單,用戶可以在其中輸入他們自己的(先前商定的)價格。

謝謝。


完整文件

服務器.js

const stripe = require('stripe')

('sk_test_51IAvl4KYIMptSkmlXwuihwZa8jtdIrnD79kSQcnhvQKbg9dbAXiZisFmasrKHIK9B75d9jgeyYK8MULLbFGrGBpU00uQgDvtnJ');
const express = require('express');
const app = express();
app.use(express.static('.'));

const YOUR_DOMAIN = 'http://localhost:4242';

var test = 2242;
console.log( amountglobal);

app.post('/create-checkout-session', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
      {
        price_data: {
          currency: 'usd',
          product_data: {
            name: 'Stubborn Attachments',
            images: ['https://i.imgur.com/EHyR2nP.png'],
          },
          unit_amount: test,
        },
        quantity: 1,
      },
    ],
    mode: 'payment',
    success_url: `${YOUR_DOMAIN}/success.html`,
    cancel_url: `${YOUR_DOMAIN}/cancel.html`,
  });

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

app.listen(4242, () => console.log('Running on port 4242'));

結帳.html

<!DOCTYPE html>
<html>
  <head>
    <title>Buy cool new product</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
    <script src="https://js.stripe.com/v3/"></script>
  </head>
  <body>
    <section>
      <div class="product">
        <img
          src="https://i.imgur.com/EHyR2nP.png"
          alt="The cover of Stubborn Attachments"
        />
        <div class="description">
          <h3>Stubborn Attachments</h3>
          <h5>$20.00</h5>
          
        </div>
      </div>
   


   
    <form id="frm12" action="#">

   First name: <input type="text" name="amount" value = "435"><br> 
<!-- <input type="button" onclick="myFunction()" value="Submit"> -->
    <input type="submit" id="checkout-button" value="Checkout">
</form>

    </section>
  </body>
  <script type="text/javascript">
    function myFunction() {
      console.log("test");
      document.getElementById("frm1").submit();
    }


    // Create an instance of the Stripe object with your publishable API key
    var stripe = Stripe("pk_test_51IAvl4KYIMptSkmlAwhNvG0CDJRnr2hyrJuRnfdnfaEEhHPwCWsr9QK183a1pKUQ4PLrrtEqiElFLTVHIiSueX6r00TyXooIcu");
    var checkoutButton = document.getElementById("checkout-button");
    var amount = document.getElementById("amount");

    amountglobal = 67865555;

    // console.log(amount);

    checkoutButton.addEventListener("click", function () {
      fetch("/create-checkout-session", {
        method: "POST",
      })
        .then(function (response) {
          return response.json();
        })
        .then(function (session) {
          console.log('here');
          return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function (result) {
          // If redirectToCheckout fails due to a browser or network
          // error, you should display the localized error message to your
          // customer using error.message.
          if (result.error) {
            alert(result.error.message);
          }
        })
        .catch(function (error) {
          console.error("Error:", error);
        });
    });
  </script>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM