Javascript 访问控制器和视图中的App.js常量
我有一个node.js express应用程序,其中包含一个Javascript 访问控制器和视图中的App.js常量,javascript,node.js,Javascript,Node.js,我有一个node.js express应用程序,其中包含一个app.js文件、一个deviceController.js文件和一个cart.pug文件。我需要在deviceController.js和cart.pug中访问条带API的两个常量,并希望在app.js中设置它们的值 我尝试了app.set/app.get,但在deviceController.js中获取了“app未定义”,我不想使用var创建全局变量 这样做的最佳实践方式是什么 app.js: const express = req
app.js
文件、一个deviceController.js
文件和一个cart.pug
文件。我需要在deviceController.js
和cart.pug
中访问条带API的两个常量,并希望在app.js
中设置它们的值
我尝试了app.set/app.get
,但在deviceController.js
中获取了“app未定义”,我不想使用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);
...
哈巴狗
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模板插值的对象,因为您的变量处于
过程中。env
难道您不能从deviceController.js
访问它们吗?@WebRookie是的,我可以,但我希望能够在app.js中为我的活动键或测试键设置常量。把它们放在一个地方是有益的