为什么acess key和secert acess key在javascript SDK中失败了?

时间:2017-03-03 11:09:30

标签: javascript amazon-web-services

我创建了一个AWS账户来连接我的网页。我有2个java脚本函数来运行AWS dynamoDB。

我可以通过直接accessKeyId和secretAccessKey连接数据库。喜欢这个代码

(function() {

// Setup basic AWS configuration
  AWS.config.update({
    region: "us-west-2",
    accessKeyId: "MY_ACESS_KEY",
    secretAccessKey: "MY_SECRET_KEY",
    logger: console
  });

 // Setup some service objects
  var docClient = new AWS.DynamoDB.DocumentClient();

  function write_to_db(Wyear,Wsports,Wname){
      var year = Wyear;
      var sports = Wsports;
      var name = Wname;
     //setting write parameters
     var params = {
        TableName :"table",
        Item:{
            "year": year,
            "sports": sports,
            "name": name
        }
    };


    //writting data 
    docClient.put(params, function(err, data) {
        if (err) {
            console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("Added item:", JSON.stringify(data, null, 2));
        }
    });
  }

 function read_from_db(Ryear,Rsports){

    var year = Ryear;
    var sports = Rsports;

    var params = {
        TableName: "table",
        Key:{
            "year": year
        }
    };

    docClient.get(params, function(err, data) {
        if (err) {
            console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
            document.getElementById("message").innerHTML = "GetItem succeeded: " + "\n" + JSON.stringify(data, null, 2);
        }
    });

 }

 function read_from_db(Ryear,Rsports){

    var year = Ryear;
    var sports = Rsports;

    var params = {
        TableName: "table",
        Key:{
            "year": year
        }
    };

    docClient.get(params, function(err, data) {
        if (err) {
            console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
            document.getElementById("message").innerHTML = "GetItem succeeded: " + "\n" + JSON.stringify(data, null, 2);
        }
    });

 }


})();

但是当我用

添加另一个JavaScript时
appInfo = {
  db: {
    region: 'us-west-2',
    tableName: 'sports_table',
    readCredentials: {
      accessKeyId: 'key',
      secretAccessKey: 'key'
    }
  }
};

并通过

访问
AWS.config.update({
    region: appInfo.db.region,
    credentials: appInfo.db.readCredentials,
    logger: console
  });

 // Setup some service objects
  var dbReader = new AWS.DynamoDB({params: {TableName: appInfo.db.tableName}});

现在它没有连接。有什么错吗?有什么建议 ?

1 个答案:

答案 0 :(得分:0)

创建AWS.Credentials的实例并使用它:

var credentials = new AWS.Credentials(
  appInfo.db.readCredentials.accessKeyId, 
  appInfo.db.readCredentials.secretAccessKey, 
  null);