【问题标题】:How to Insert dynamic script in Angular based on environment variable in Nodejs如何根据Nodejs中的环境变量在Angular中插入动态脚本
【发布时间】:2016-01-14 16:07:40
【问题描述】:

我在 Angular 应用程序中的 index.html 文件底部有一个脚本,我想根据 Node.js 中的环境变量对其进行更改。我想将一个公共 api 密钥用于暂存,另一个用于生产。

我对登台和生产使用相同的 grunt 构建,所以我不知道是否按照建议 here 动态更改构建时的常量是最好的解决方案。

关于如何处理这个问题有什么想法吗?

当环境变量为 NODE_ENV=production 时,插入:

 <script>
 Stripe.setPublishableKey('pk_live_NN4j94VX3mtz2wJtIO3bmH');
 </script>

当环境变量为 NODE_ENV=staging 时,插入:

<script>
 Stripe.setPublishableKey('pk_test_LgtEvbZwjC2GaKQYE3I6NnzuA');
</script>

【问题讨论】:

  • 在构建时动态改变常量确实是唯一的好方法,我不知道你会如何处理它。在某些地方您需要读取或切换环境变量,如果该变量恰好是您的构建控件的一部分,那么放置它是一个不错的地方。如果您想要一个角度较小的解决方案,那么您可以在您的角度构建之前包含一个全局配置 js 脚本。
  • 创建一个配置模块可能不是一个坏主意。 (基本上是一个导出的 JSON 对象),以便您可以使用基于环境变量的变量。

标签: angularjs node.js environment-variables stripe-payments


【解决方案1】:

我会使用grunt-ng-constant 来管理您的角度环境变量,然后在您的角度app.config() 函数而不是您的文档中初始化Stripe。

我的偏好是使用 angular-stripe 在 Angular 启动过程中管理 Stripe。如果您使用两个键配置应用程序,这也可能使您的生活更轻松。这是我的一个应用程序中的一些示例代码。

var $app = angular.module('app', ['angular-stripe']);
$app.constant('devDomains', ['localhost', 'staging.mydomain.com']);
$app.constant('stripePubKeyStaging', 'STRIPE_PUB_KEY_HERE');
$app.constant('stripePubKey', 'STRIPE_PUB_KEY_HERE');

$app.config(function(devDomains, stripePubKey, stripePubKeyStaging, stripeProvider) {
  if (devDomains.indexOf(document.location.hostname) !== -1 || document.location.search.indexOf('stripe-test-key') !== -1) {

    // if you're running your angular app on local or staging, use the test key. Additionally 
    // if you load your page with ?stripe-test-key you can force your production app 
    // to use the test key in order to debug something on live if you'd like.
    stripeProvider.setPublishableKey(stripePubKeyStaging);
  } else {
    stripeProvider.setPublishableKey(stripePubKey);
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 2021-07-14
    • 2013-07-09
    • 1970-01-01
    • 2013-09-01
    • 2018-04-02
    • 2023-03-28
    相关资源
    最近更新 更多