Nodejs调用函数和变量范围问题; ConfigError:配置中缺少区域

时间:2017-06-26 11:00:44

标签: node.js prototype amazon-dynamodb aws-sdk

我是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
    });
};

1 个答案:

答案 0 :(得分:0)

在配置更新后移动dynamodbClientdynamoDocClient行。

示例: -

aws.config.update({
        region: dynamoConfig.region,
        endpoint: dynamoConfig.url
    });
const dynamodbClient = new aws.DynamoDB();
const dynamoDocClient = new aws.DynamoDB.DocumentClient();