我正面临一个问题。我想从angularjs传递键,然后在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;
但当然这不起作用。如何使用之前保存的值来阅读constants
?
答案 0 :(得分:2)
你应该有 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.
}