概览
基于自动生成的JavaScript SDK的AWS API网关客户端模块. 此模块不仅可用于Node.js,也可用于前端. 此外,它还概括了原始SDK的端点特有方法.
先决条件
为了JavaScript SDK工作,你的API需要支持CORS. 亚马逊 API 网关开发者指南 解释如何 为终点设置 CORS。 。 。 .
V1-V2少校弹出
在将轴从0.26.1更新到1.6.2的过程中,我们发现,使用滑稽测试的重置可能会遇到嘲弄的问题,因此如果你从消耗v1转向v2,请注意这一差异. 有关于一些共同问题和解决的共同文件.
安装
npm install @adastradev/aws-api-gateway-client
在您的工程中使用 SDK
需要模块
var apigClientFactory = require('aws-api-gateway-client').default;
设定引用Url配置并创建客户端 。 如需授权,须提供补充资料,说明如下.
config = {invokeUrl:'https://xxxxx.execute-api.us-east-1.amazonaws.com'}
var apigClient = apigClientFactory.newClient(config);
要求建立API的形式如下: 每个API呼叫返回一个承诺, 它引用成功和失败的回调
var pathParams = {
//This is where path request params go.
userId: '1234',
};
// Template syntax follows url-template https://www.npmjs.com/package/url-template
var pathTemplate = '/users/{userID}/profile'
var method = 'GET';
var additionalParams = {
//If there are query parameters or headers that need to be sent with the request you can add them here
headers: {
param0: '',
param1: ''
},
queryParams: {
param0: '',
param1: ''
}
};
var body = {
//This is where you define the body of the request
};
apigClient.invokeApi(pathParams, pathTemplate, method, additionalParams, body)
.then(function(result){
//This is where you would put a success callback
}).catch( function(result){
//This is where you would put an error callback
});
使用 AWS IAM 进行授权
要以 AWS 证书初始化 SDK 使用下面的代码. 注意, 如果您使用证书, 所有对 API 的请求都会被签名 。 这意味着您将不得不为每个请求设置相应的 CORS 接受-* 标题 .
var apigClient = apigClientFactory.newClient({
invokeUrl:'https://xxxxx.execute-api.us-east-1.amazonaws.com', // REQUIRED
region: 'eu-west-1', // REQUIRED: The region where the API is deployed.
accessKey: 'ACCESS_KEY', // REQUIRED
secretKey: 'SECRET_KEY', // REQUIRED
sessionToken: 'SESSION_TOKEN', // OPTIONAL: If you are using temporary credentials
you must include the session token.
systemClockOffset: 0, // OPTIONAL: An offset value in milliseconds to apply to signing time
retries: 4, // OPTIONAL: Number of times to retry before failing. Uses axios-retry plugin.
retryCondition: (err) => { // OPTIONAL: Callback to further control if request should be retried.
return err.response && err.response.status === 500; // Uses axios-retry plugin.
},
retryDelay: 100 || 'exponential' || (retryCount, error) => { // OPTIONAL: Define delay (in ms) as a number, a callback, or
return retryCount * 100 // 'exponential' to use the in-built exponential backoff
} // function. Uses axios-retry plugin. Default is no delay.
});
使用 API 密钥
要使用客户端 SDK 的 API 密钥, 您可以将密钥作为参数传递到 Factory 对象 。 注意, 如果您使用 apiKey , 它将作为标题“ x- api- key” 附加到 API 的所有请求上 。 这意味着您将不得不为每个请求设置相应的 CORS 接受-* 标题 .
var apigClient = apigClientFactory.newClient({
invokeUrl:'https://xxxxx.execute-api.us-east-1.amazonaws.com', // REQUIRED
apiKey: 'API_KEY', // REQUIRED
region: 'eu-west-1' // REQUIRED
});