【问题标题】:NodeJs Separate Dev and Prod Environment VariablesNodeJs 分离 Dev 和 Prod 环境变量
【发布时间】:2021-06-18 02:17:45
【问题描述】:

我有一个 nodejs 服务器,在我的服务文件中,我从我创建的 config.json 文件中获取请求的 URL,如下所示。问题是我想对开发使用不同的变量 url,对生产使用不同的变量 url。换句话说,当在开发环境中运行时,URL 应该从 config.json 文件运行 prod url,而在 config.json 中运行 dev url。我对 nodejs 中的环境变量不熟悉,因此将不胜感激。

我的 service.js 文件之一是:

const config = require('../config');



async function getOrderLineItems(data) {
  const options = {
    method: 'GET',
    url: config.cloverApiUrl ,
    headers: {
      Authorization: 'Bearer ' + data.token,
      ContentType: 'application/json'
    },
  };
  const response = await got(options);
  return response.body;
}

我的 config.json 文件是:

{
    "connectionString": "connectionString",
    "secret": "secret",
    "cloverApiUrl": "cloverApiUrl",
    "clientSecret": "clientSecret",
    "keyUrl": "keyUrl",
    "tokenUrl": "tokenUrl"
}

【问题讨论】:

    标签: node.js express environment-variables backend production-environment


    【解决方案1】:

    您可以有两个配置文件,一个用于生产,一个用于开发,使用 process.env.NODE_ENV 将返回当前环境,并且通过一个简单的条件,您可以决定需要哪个文件(如果这可能是另一个带有 env 的对象作为键,require 语句作为值)

    let config;
    if(process.env.NODE_ENV === 'production'){
     config = require('path/to/config.prod.json');
    }else if....
    
    //or something like this
    const config = require('config.json')[process.env.NODE_ENV]
    //where config is something like this
    
    module.export = {
     'production':{...},
     'development':{...}
    }
     
    

    您可以在脚本中添加 NODE_ENV=... 来决定环境

    "server": "NODE_ENV=development nodemon index.js",
    

    【讨论】:

      【解决方案2】:

      解决方案 1:

      要么安装配置包。

      项目目录如下所示,

      配置

      • default.json

      https://www.npmjs.com/package/config

      1. 否则在项目目录中创建一个 .env 文件,然后通过 process.en.variable_name 访问它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-30
        • 1970-01-01
        • 2022-01-16
        • 1970-01-01
        • 2018-04-24
        • 2022-12-07
        • 2019-07-31
        • 2021-09-22
        相关资源
        最近更新 更多