准备浏览器脚本 - AWS SDK for JavaScript

帮助我们改进AWS SDK for JavaScript版本 3 (V3) 文档,方法是使用反馈链接,或者在上创建议题或拉取请求GitHub.

这些区域有:AWS SDK for JavaScriptV3 API 参考指南详细描述了所有的 API 操作AWS SDK for JavaScript版本 3 (V3)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

准备浏览器脚本

本主题是教程的一部分,该教程演示了如何使用AWS SDK for JavaScript. 要开始使用本教程,请参阅创建和使用 Lambda 函数

首先,创建所需的服务客户端对象。创建libs文件夹,然后在其中创建两个文件,dynamoClient.jslambdaClient.js. 将下面的代码粘贴到dynamoClient.js.

const { CognitoIdentityClient } = require ( "@aws-sdk/client-cognito-identity" ); const { fromCognitoIdentityPool } = require ( "@aws-sdk/credential-provider-cognito-identity" ); const { DynamoDBClient } = require ( "@aws-sdk/client-dynamodb" ); const REGION = "REGION"; const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID. // Create an Amazon DynamoDB service client object. const dynamoClient = new DynamoDBClient({ region: REGION, credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region: REGION }), identityPoolId: IDENTITY_POOL_ID, }), }); module.exports = { dynamoClient };

将下面的代码粘贴到lambdaClient.js.

const { lambdaClient } = require ("@aws-sdk/client-lambda" ); const { fromCognitoIdentityPool, } = require ( "@aws-sdk/credential-provider-cognito-identity" ); const { CognitoIdentityClient } = require ("@aws-sdk/client-cognito-identity" ); // Set the AWS Region. const REGION = "eu-west-1"; // e.g., 'us-east-2' const IDENTITY_POOL_ID = "eu-west-1:dc7d706a-1f07-4fa5-baa7-edfabc05f293"; // Create an AWS Lambda client service object that initializes the Amazon Cognito credentials provider. const lambdaClient = new LambdaClient({ region: REGION, credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region: REGION }), identityPoolId: IDENTITY_POOL_ID }), }); module.exports = {lambdaClient}

在两者中,替换领域使用AWS区域。如图所示创建 Lambda 客户端服务对象。ReplaceIDENTITY_POOL_ID使用IdentityPoolId您在创建AWS资源 本教程的主题。

LambdaApp文件夹中,创建一个文件名index.js,然后将下面的内容粘贴到其中。

// Load the required clients and packages. const { InvokeCommand } = require ("@aws-sdk/client-lambda" ); const { lambdaClient } = require ( "../libs/lambdaClient" ); // Set the parmaeters. const params={ // The name of the AWS Lambda function. FunctionName: "LAMBDA_FUNCTION", InvocationType: "RequestResponse", LogType: "None" } // Call the Lambda function. window.createTable = async () => { try { const data = await lambdaClient.send(new InvokeCommand(params)); console.log("Table Created", data); document.getElementById('message').innerHTML = "Success, table created" } catch (err) { console.log("Error", err); } };

在参数中,替换LAMBDA_函数你的名字是唯一的AWS例如,帐户createTable.

此代码示例可用此处GitHub.

最后,在命令提示符下运行以下命令以将JavaScript对于此示例,在名为的文件中main.js.

webpack LambdaApp/index.js --mode development --target web --devtool false -o LambdaApp/main.js
注意

有关安装的信息,请参阅使用 webpack 捆绑应用程序.