【问题标题】:Using global variables properly in node.js or is there a better way of doing this?在 node.js 中正确使用全局变量,或者有更好的方法吗?
【发布时间】:2021-02-05 09:45:20
【问题描述】:

我正在尝试从我的 checkout.html 文件(如下)中获取用户输入的金额,以便我可以在 server.js 上的 Stripe 代码中使用它节点服务器。

我无法从表单中获取amount field,因此我禁用了它并正在使用console.log 和变量。我试图让它与传递值的全局变量一起工作。

Stripe 网站上示例中的这 2 个文件(您从页面中选择“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 gloabal var),那么由于某种原因服务器不会启动,说 amountglobal 不是已定义...所以我可能在 checkout.html 中有错误的全局变量,它是

amountglobal = 67865555;

...也许一开始就有更好的方法,我知道全局变量通常不是理想的。

这里的最终结果是一个付款表单,用户可以在其中输入他们自己的(之前商定的)价格。

谢谢。


完整文件

server.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'));

Checkout.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>

【问题讨论】:

  • 看来您可能不明白您的浏览器客户端 Javascript 运行在与您的服务器 Javascript 完全不同的世界(不同的计算机、不同的网络、不同的进程、不同的 JS 引擎)中。您不能在它们之间共享全局变量。即使你想这样做,即使你可以这样做,无论如何这都是错误的设计。相反,您必须将数据从客户端发送到服务器。
  • 在表单中,您可以将表单 POST 到您的服务器(使用 HTML 表单和适当的表单操作,或者使用带有 Javascript 的 Ajax 调用),然后正确读取表单正文并解析它在您的服务器上获取数据。然后,您可以使用该数据在服务器上执行任何操作,然后将某种结果返回给客户端。服务器和客户端是完全独立的 Javascript 世界。他们仅通过将数据从一个发送到另一个来共享数据。
  • 最后得到了这个排序 - 进行了一些学习和 T&E - 感谢这些 cmets 的帮助。将根据元建议在代码审查中发布完成的代码,然后再进行整理等和样式;-)

标签: javascript node.js stripe-payments


【解决方案1】:

【讨论】:

  • 我决定切换到 php 示例。我想我知道你在这里的意思,但是使用 php 版本是否适用相同的原则,或者会有什么不同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多