如何使用Angular向API网关发出Get请求?

时间:2019-03-15 17:58:00

标签: angular amazon-web-services aws-api-gateway

我正在尝试点击以下 AWS 端点:

https://abcde12345hf.execute-api.us-east-2.amazonaws.com/dev/users

返回:

[{
  "id": 1,
  "name": "Mike"
},{
  "id": 2,
  "name": "Brian"
}]
  • 在我的Angular代码中,我正在使用AWS4库发送 secretAccessKey accessKeyId sessionToken 来验证用户身份,但出现以下错误:
  

core.js:12501错误错误:未捕获(承诺):错误:请求   失败了       状态码403       错误:请求失败,状态码为403

  • 有人知道如何正确地将 AWS4 与Angular结合使用,以便进行简单的GET调用吗?还是有人知道使用这些密钥和令牌进行身份验证的另一种方法吗?提前谢谢!

这是我获取密钥和令牌的方式(这部分效果很好)

AWS.config.region = 'us-east-2';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'us-east-2:ehkjthf-sf23-12ds-xxxxxxxxx',
    Logins: {
        'cognito-idp.us-east-2.amazonaws.com/us-east-2_Raxxxx': this.id_token
    }
});

console.log(AWS.config.credentials);

现在,这就是我使用这些键和令牌进行GET调用的方式。

(AWS.config.credentials as AWS.Credentials).get(function(error: AWSError){
  if(error){
    console.log('Error ', error);
  }else{
  let request = {
    host: 'https://abcde12345hf.execute-api.us-east-2.amazonaws.com/dev/users',
    method: 'GET',
    url:  'https://abcde12345hf.execute-api.us-east-2.amazonaws.com/dev/users',
    path: '/users',
    headers: {
      "Content-Type":"application/json"
    },
  }

  let signedRequest = aws4.sign(request,
    {
      secretAccessKey: AWS.config.credentials.secretAccessKey,
      accessKeyId: AWS.config.credentials.accessKeyId,
      sessionToken: AWS.config.credentials.sessionToken
    });

    delete signedRequest.headers['Host']
    delete signedRequest.headers['Content-Length']

    axios(signedRequest).then((response) =>{
      console.log(response); // Output the Array Object here
    });
  }
});

1 个答案:

答案 0 :(得分:4)

我让它工作了,我会分享我的解决方案,以防其他人需要它!

我最终从角度而不是axios使用 http服务。这是我的解决方案;

(AWS.config.credentials as AWS.Credentials).get((error: AWSError) =>{
 if(error){
   console.log('Error ', error);
 }else{
 let request = {
   host: 'abcdefg.execute-api.us-east-2.amazonaws.com',
   method: 'GET',
   url:  `https://abcdefg.execute-api.us-east-2.amazonaws.com/dev/users`,
   path: '/dev/users'
 }

  let signedRequest = aws4.sign(request, {
    secretAccessKey: AWS.config.credentials.secretAccessKey,
    accessKeyId: AWS.config.credentials.accessKeyId,
    sessionToken: AWS.config.credentials.sessionToken
  });
  delete signedRequest.headers['Host'];
  this.http.get(signedRequest.url, signedRequest).subscribe(res => this.myObject = res);
 }
}