代码之家  ›  专栏  ›  技术社区  ›  Tarun

从nodejs常量文件读取常量

  •  0
  • Tarun  · 技术社区  · 6 年前

    我面临一个问题。我想通过 钥匙 然后在nodejs中使用它在一些常量中搜索该键。

    我有以下对我的服务器的调用:

         $http({
                method: 'POST',
                url: 'http://localhost:1620,
                headers: {
                    'Content-Type': 'application/json; charset=utf-8',
                },
                data: {
                    data: dataObj
                }
    
            }).then(function (response) {
                deferred.resolve(response.data);
    
            }, function (failureResponse) {
                deferred.reject({
                    error: 'Error while getting the data'
                });
            });
    

    在我的节点服务器中,我收到值:

    var apiConstant = req.params('apiConstant');
    

    现在 钥匙 是在 apiConstant . 我想用这个值来读取 constants

    var constants = require('path to constant file');
    
    var val = constants.COMPANY_ADD; 
    

    但这当然行不通。如何使用以前保存的值进行读取 常量 ?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Sampgun    6 年前

    你应该有一个 JS型

    'use strict';
    
    //exports.model = myModel;
    
    var tmp = {
        foo: "bar"
    };
    
    exports.constants = Object.freeze(tmp);
    

    索引.js

    var model = require("./path-to/model");
    myConstants = model.constants; //this makes the variable accessible from everywhere, because without 'var' you're creating a global
    

    以及在哪里接收数据

    var constantsKey = req.params('apiConstant');
    
    if(!!myConstants[constantsKey]){
       //do stuff, you can also avoid this control if you don't need it.
    
    }