我是Nodejs的新手,并且一直受到这个问题的困扰,我确信这与NodeJ中的变量范围有关,但是我有一段时间无法理解它。
问题 - >为什么以下程序的输出如下:
ConfigError:配置中缺少区域
##server.js##
`const aws = require('aws-sdk');
const dynamoConfig = require('./database');
const dynamodbClient = new aws.DynamoDB();
const dynamoDocClient = new aws.DynamoDB.DocumentClient();
aws.config.update({
region: dynamoConfig.region,
endpoint: dynamoConfig.url
});
function userRegistrationDB(tableName) {
this.tableName = tableName;
};
userRegistrationDB.prototype.init = function() {
// body...
aws.config.update({
region: dynamoConfig.region,
endpoint: dynamoConfig.url
});
};
userRegistrationDB.prototype.putItem = function(userid, username) {
// body...
var param = {
TableName: this.tableName,
Item: {
"id": userid,
"name": username
}
};
console.log('updating item in table '+this.tableName);
var res = dynamoDocClient.put( param, function(err, data){
if(err) console.log('error ->'+err);
else console.log(data+"success");
});
};
module.exports = userRegistrationDB;
var obj = new userRegistrationDB('UserRegistration');
obj.init();
obj.putItem(123,'test2');
##database.js##
module.exports ={
'region': 'us-west-2',
'url': 'http://localhost:8000'
};
此外,任何一个函数都能够正确地从database.js中获取值:
aws.config.update({
region: dynamoConfig.region,
endpoint: dynamoConfig.url
});
userRegistrationDB.prototype.init = function() {
// body...
aws.config.update({
region: dynamoConfig.region,
endpoint: dynamoConfig.url
});
};
答案 0 :(得分:0)
在配置更新后移动dynamodbClient
和dynamoDocClient
行。
示例: - 强>
aws.config.update({
region: dynamoConfig.region,
endpoint: dynamoConfig.url
});
const dynamodbClient = new aws.DynamoDB();
const dynamoDocClient = new aws.DynamoDB.DocumentClient();