我有一个带有 app.js
的 Node.js Express 应用程序文件,a deviceController.js
文件,以及 cart.pug
文件。我需要访问 deviceController.js
中 Stripe API 的两个常量和cart.pug
并希望将其值设置为 app.js
.
我试过app.set/app.get
但在 deviceController.js
中得到“应用程序未定义”我不想用var
创建一个全局变量.
执行此操作的最佳实践方法是什么?
app.js:
const express = require('express');
const routes = require('./routes/index');
const app = express();
// **want these constants available in deviceController.js and cart.pug**
const keyPublishable = process.env.PUBLISHABLE_KEY;
const keySecret = process.env.SECRET_KEY;
app.set('view engine', 'pug');
module.exports = app;
deviceController.js
...
const stripe = require('stripe')(keySecret);
...
购物车.pug
extends layout
...
block content
.inner
form(action="/payment" method="POST")
script(
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key=keyPublishable
...)
最佳答案
您应该为流程常量创建一个模块 - 这样您就可以在任何地方需要它们,而无需直接访问流程。
// constants.js
module.exports = {
stripe: { // you could also use stripeKeys or whatever
keyPublishable: process.env.PUBLISHABLE_KEY;
keySecret: process.env.SECRET_KEY;
}
}
然后在每个文件中
// deviceController.js
const { stripe } = require('./constants.js');
// use stripe.keyPublishable or stripe.keySecret
以及模板中
// when compiling the pug file, you also require the constants file and pass it
// template.pug has #{keyPublishable}
const { stripe } = require('./constants.js');
// .. rest of code
pug.renderFile('template.pug', {
keyPublishable : stripe.keyPublishable
}));
查看有关如何传递要由 pug 模板插值的对象的文档
关于javascript - 在 Controller 和 View 中访问 App.js 常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55536682/