在 node.js 中正确使用全局变量还是有更好的方法? [英] Using global variables properly in node.js or is there a better way of doing this?

查看:27
本文介绍了在 node.js 中正确使用全局变量还是有更好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我无法从表单中获取 amount 字段,所以我禁用了它并使用 console.log 和变量.我试图让它与传递值的全局变量一起工作.

来自 Stripe 网站示例的这 2 个文件(您从页面中选择node"和html",然后点击预构建"强>'也)

POST 到服务器端代码,然后使用 带有 Express 的 JSON 正文解析器,以便它在服务器端请求中结束.

I am trying to get a user entered amount from my checkout.html file ( below ) so that I can use it in the Stripe code on the server.js node server.

I wasn't able to get the amount field from the form to work so I disabled it and am working with console.log and variables. I was trying to make it work with a global variable passing the value.

These 2 files from the example on the Stripe website ( you select 'node' and 'html' from the page, and click 'prebuilt' also )

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

My alterations ( sorry the var assignments numbers are all just random for testing )

**server.js** 

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


( line 22 )
unit_amount: test, 


**checkout.html** (line 47 )

amountglobal = 67865555;

My issue is that if I uncomment line 9 ( with the aim of trying to use the amountglobal gloabal var in line 22 ) then for some reason the server wont start, saying amountglobal is not defined ... so I possibly have the global variable wrong in checkout.html, it's

amountglobal = 67865555;

... and maybe there's a better way of doing this in the first place, I understand global variables are not the ideal usually.

The end result here is to be a payment form where the user can type in their own ( previously agreed) price.

Thanks.


FULL FILES

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>

解决方案

You need to POST the data from your client side code to your server side code, and then use a JSON body parser with Express so that it ends up in the server-side request.

这篇关于在 node.js 中正确使用全局变量还是有更好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆