【发布时间】:2017-12-17 16:56:17
【问题描述】:
我正在尝试使用 aws-sdk/dist/aws-sdk-react-native 和常规的 fetch 调用从 React Native 应用程序调用 API 网关端点。
API Gateway 端点需要 IAM 授权。为此,我设置了一个 AWS Cognito 联合身份池,并将未经身份验证的 IAM 角色配置为对 API 具有执行权限。
下面的代码在我的 React Native 应用程序上运行,应该从 Cognito 获取一个新令牌并使用它来签署对 API 网关端点的请求。不幸的是,每次我运行它时,我都会收到一个 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)
});
});
【问题讨论】:
标签: javascript amazon-web-services react-native aws-api-gateway aws-cognito