Closed5

【AWS公式チュートリアル】「基本的なウェブアプリケーションを構築する」におけるエラー改善メモ

noknok

今回の進め方

  • チュートリアルに沿って、全てAWSコンソール上での作業とする
  • Lambdaでのコーディング部分は、「Javascript」での実装とした(ランタイム設定: Nod.js 20.x)
noknok

「モジュール 2: サーバーレス関数を構築する」でのエラー対応

概要

実装したコードと、エラー内容

  • コード
// Define handler function, the entry point to our code for the Lambda service
// We receive the object that triggers the function as a parameter
exports.handler = async (event) => {
    // Extract values from event and format as strings
    let name = JSON.stringify(`Hello from Lambda, ${event.firstName} ${event.lastName}`);
    // Create a JSON object with our response and store it in a constant
    const response = {
        statusCode: 200,
        body: name
    };
    // Return the response constant
    return response;
};
  • エラー内容
Response
{
  "errorType": "ReferenceError",
  "errorMessage": "exports is not defined in ES module scope",
  "trace": [
    "ReferenceError: exports is not defined in ES module scope",
    "    at file:///var/task/index.mjs:3:1",
    "    at ModuleJob.run (node:internal/modules/esm/module_job:222:25)",
    "    at async ModuleLoader.import (node:internal/modules/esm/loader:316:24)",
    "    at async _tryAwaitImport (file:///var/runtime/index.mjs:1008:16)",
    "    at async _tryRequire (file:///var/runtime/index.mjs:1057:86)",
    "    at async _loadUserApp (file:///var/runtime/index.mjs:1081:16)",
    "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)",
    "    at async start (file:///var/runtime/index.mjs:1282:23)",
    "    at async file:///var/runtime/index.mjs:1288:1"
  ]
}

修正後コード

  • 「exports.handler = 〜」は、古いNode.jsバージョンのエクスポート形式。
    そのため、「export const handler = 〜」の形式に修正する
// Define handler function, the entry point to our code for the Lambda service
// We receive the object that triggers the function as a parameter
-- exports.handler = async (event) => {
++ export const handler = async (event) => {
    // Extract values from event and format as strings
    let name = JSON.stringify(`Hello from Lambda, ${event.firstName} ${event.lastName}`);
    // Create a JSON object with our response and store it in a constant
    const response = {
        statusCode: 200,
        body: name
    };
    // Return the response constant
    return response;
};

参考サイト

noknok

「モジュール 4: データテーブルを作成する」でのエラー対応

概要

実装したコードと、エラー内容

  • コード
// Include the AWS SDK module
const AWS = require('aws-sdk');
// Instantiate a DynamoDB document client with the SDK
let dynamodb = new AWS.DynamoDB.DocumentClient();
// Use built-in module to get current date & time
let date = new Date();
// Store date and time in human-readable format in a variable
let now = date.toISOString();
// Define handler function, the entry point to our code for the Lambda service
// We receive the object that triggers the function as a parameter
exports.handler = async (event) => {
    // Extract values from event and format as strings
    let name = JSON.stringify(`Hello from Lambda, ${event.firstName} ${event.lastName}`);
    // Create JSON object with parameters for DynamoDB and store in a variable
    let params = {
        TableName:'HelloWorldDatabase',
        Item: {
            'ID': name,
            'LatestGreetingTime': now
        }
    };
    // Using await, make sure object writes to DynamoDB table before continuing execution
    await dynamodb.put(params).promise();
    // Create a JSON object with our response and store it in a constant
    const response = {
        statusCode: 200,
        body: name
    };
    // Return the response constant
    return response;
};
  • エラー内容
{
  "errorType": "ReferenceError",
  "errorMessage": "require is not defined in ES module scope, you can use import instead",
  "trace": [
    "ReferenceError: require is not defined in ES module scope, you can use import instead",
    "    at file:///var/task/index.mjs:2:13",
    "    at ModuleJob.run (node:internal/modules/esm/module_job:222:25)",
    "    at async ModuleLoader.import (node:internal/modules/esm/loader:316:24)",
    "    at async _tryAwaitImport (file:///var/runtime/index.mjs:1008:16)",
    "    at async _tryRequire (file:///var/runtime/index.mjs:1057:86)",
    "    at async _loadUserApp (file:///var/runtime/index.mjs:1081:16)",
    "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)",
    "    at async start (file:///var/runtime/index.mjs:1282:23)",
    "    at async file:///var/runtime/index.mjs:1288:1"
  ]
}

修正後コード

  • AWS SDKのインポート形式を「require」から「import」に変更、かつ、各サービス毎に読み込む形式に変更
    ※1:「require」はNode.js v14以降から使えなくなった模様。そのため「import」を利用する
    ※2:「AWS SDK for JavaScript v3」からは、"aws-sdk"のみでインポート出来なくなった模様
  • エクスポート形式を、「export const handler = 〜」の形式に修正
  • データ入力方法を、「PutCommand」メソッドを使った形式に修正
// Include the AWS SDK module
-- const AWS = require('aws-sdk');
++ import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
++ import { PutCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
// Instantiate a DynamoDB document client with the SDK
-- let dynamodb = new AWS.DynamoDB.DocumentClient();
++ const dynamodb = new DynamoDBClient();
++ const docClient = DynamoDBDocumentClient.from(dynamodb);
// Use built-in module to get current date & time
let date = new Date();
// Store date and time in human-readable format in a variable
let now = date.toISOString();
// Define handler function, the entry point to our code for the Lambda service
// We receive the object that triggers the function as a parameter
-- exports.handler = async (event) => {
++ export const handler = async (event) => {
    // Extract values from event and format as strings
    let name = JSON.stringify(`Hello from Lambda, ${event.firstName} ${event.lastName}`);
    // Create JSON object with parameters for DynamoDB and store in a variable
--     let params = {
--         TableName:'HelloWorldDatabase',
--         Item: {
--             'ID': name,
--             'LatestGreetingTime': now
--         }
--     };
++     const command = new PutCommand({
++         TableName:'HelloWorldDatabase',
++         Item: {
++             'ID': name,
++             'LatestGreetingTime': now
++         }
++     });
    // Using await, make sure object writes to DynamoDB table before continuing execution
--     await dynamodb.put(params).promise();
++     await docClient.send(command);
    // Create a JSON object with our response and store it in a constant
    const response = {
        statusCode: 200,
        body: name
    };
    // Return the response constant
    return response;
};

参考サイト

noknok

チュートリアル全体を確認することができたため、クローズします。

このスクラップは4ヶ月前にクローズされました