从 nodejs 常量文件中读取常量

Reading constants from nodejs constants file

我遇到了一个问题。我想从 angularjs 传递一个 key 然后在 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');

现在 keyapiConstant 中。 我想使用该值从 constants

读取
var constants = require('path to constant file');

var val = constants.COMPANY_ADD; 

但这当然行不通。如何使用之前保存的值读取 constants?

你应该有一个model.js

'use strict';

//exports.model = myModel;

var tmp = {
    foo: "bar"
};

exports.constants = Object.freeze(tmp);

一个index.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.

}