在 node.js 中正确使用全局变量还是有更好的方法?
Using global variables properly in node.js or is there a better way of doing this?
我正在尝试从我的 checkout.html 文件(如下)中获取用户输入的金额,以便我可以在 [=42] 的 Stripe 代码中使用它=]server.js 节点服务器.
我无法让表单中的 amount field
正常工作,所以我禁用了它并使用 console.log 和变量。我试图让它与传递值的全局变量一起工作。
来自 Stripe 网站示例的这 2 个文件(您 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
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>.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>
您需要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。
我正在尝试从我的 checkout.html 文件(如下)中获取用户输入的金额,以便我可以在 [=42] 的 Stripe 代码中使用它=]server.js 节点服务器.
我无法让表单中的 amount field
正常工作,所以我禁用了它并使用 console.log 和变量。我试图让它与传递值的全局变量一起工作。
来自 Stripe 网站示例的这 2 个文件(您 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
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>.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>
您需要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。