使用来自React Native

时间:2017-07-13 04:50:34

标签: javascript amazon-web-services react-native aws-api-gateway aws-cognito

我正在尝试使用aws-sdk/dist/aws-sdk-react-native和常规fetch调用从React Native应用程序调用API网关端点。 API网关端点需要IAM授权。为此,我设置了一个AWS Cognito联合身份池,并配置了未经身份验证的IAM角色,以获得对API的执行权限。

以下代码在我的React Native应用程序上运行,并且应该从Cognito获取新令牌并使用它来签署对API Gateway端点的请求。不幸的是,每次运行它时都会收到如下的html错误响应:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD><BODY>
<H1>ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Bad request.
<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: fiYpmNCsqwm7D9yUjNOmBCLisxtKNBiV2EO6X-eeKpbpmwk6rkkMJQ==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>

我无法弄清楚我做错了什么......

import AWS from 'aws-sdk/dist/aws-sdk-react-native';

let region = 'us-west-2';
AWS.config.region = region;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'xxxxxxxxxxxx',
});

let host = 'https://xxxxxxx.execute-api.us-west-2.amazonaws.com';
let route = '/beta/api/foo';
let url = `${host}${route}`;

AWS.config.credentials.get(function(err) {
    console.log('AWS.config.credentials', AWS.config.credentials);

    var httpRequest = new AWS.HttpRequest(url);
    httpRequest.method = 'GET';
    httpRequest.path = route;
    httpRequest.region = region;
    httpRequest.headers['Host'] = host;
    httpRequest.headers['Content-Type'] = "application/json";

    var service = "execute-api";
    var v4signer = new AWS.Signers.V4(httpRequest, service);
    v4signer.addAuthorization(AWS.config.credentials, new Date());

    fetch(url, httpRequest)
        .then( resp => {
           console.log('API gateway response', resp)
           // Should receive JSON, but currently getting text with HTML error message
           // return resp.json();
           return resp.text();
        })
        .then(txt => {
           console.log("API Gateway result", txt)
        })
        .catch( err => {
           console.log('Failed call to API Gateway', err)
        });
});

1 个答案:

答案 0 :(得分:0)

如上所述,您的代码会将主机标头设置为&#39; https://xxxxxxx.execute-api.us-west-2.amazonaws.com&#39;

主机标题应该只包含主机的DNS名称,因此它应该只是&#39; xxxxxxx.execute-api.us-west-2.amazonaws.com&#39;