aws-amplify / amplify-js

A declarative JavaScript library for application development using cloud services.
https://docs.amplify.aws/lib/q/platform/js
Apache License 2.0
9.43k stars 2.13k forks source link

REST API - Internal Server Error 502 #11391

Closed xanderbilla closed 1 year ago

xanderbilla commented 1 year ago

Before opening, please confirm:

JavaScript Framework

React

Amplify APIs

REST API

Amplify Categories

auth, storage, api

Environment information

``` # Put output below this line System: OS: Windows 10 10.0.22621 CPU: (8) x64 Intel(R) Core(TM) i5-9300H CPU @ 2.40GHz Memory: 2.66 GB / 7.91 GB Binaries: Node: 18.16.0 - C:\Program Files\nodejs\node.EXE npm: 9.6.1 - C:\Program Files\nodejs\npm.CMD Browsers: Edge: Spartan (44.22621.1702.0), Chromium (113.0.1774.42) Internet Explorer: 11.0.22621.1 npmPackages: @aws-amplify/ui-react: ^4.6.2 => 4.6.2 @aws-amplify/ui-react-internal: undefined () @testing-library/jest-dom: ^5.16.5 => 5.16.5 @testing-library/react: ^13.4.0 => 13.4.0 @testing-library/user-event: ^13.5.0 => 13.5.0 aws-amplify: ^5.2.2 => 5.2.2 react: ^18.2.0 => 18.2.0 react-dom: ^18.2.0 => 18.2.0 react-router-dom: ^6.11.2 => 6.11.2 react-scripts: 5.0.1 => 5.0.1 web-vitals: ^2.1.4 => 2.1.4 npmGlobalPackages: @aws-amplify/cli: 10.8.1 json-server: 0.17.3 npm: 9.6.1 serverless: 3.30.1 ```

Describe the bug

Hello dev,

I initialized aws amplify application with default configuration.

After that I added Storage (Dynamo DB) and added some column and also GSI and sort key

After that I added api where I created new lambda function and also added the DynamoDB table in that function. After pushing the code I tested API (with default written function) it worked fine for all methods (get, post)

But, when I made some changes like adding item and retrieving item from table in lambda function and tested it returns 502 error

I have also provided the API logs but it's saying aws-sdk not found to some unknown module

Expected behavior

The expected behvior is it should work for post and get method

Reproduction steps

While using the methods it appears with status code 502

Code Snippet

// Put your code below this line.
/*
Copyright 2017 - 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
    http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
*/

/* Amplify Params - DO NOT EDIT
    ENV
    REGION
    STORAGE_MYORDERSDB_ARN
    STORAGE_MYORDERSDB_NAME
    STORAGE_MYORDERSDB_STREAMARN
Amplify Params - DO NOT EDIT */

const express = require('express')
const bodyParser = require('body-parser')
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')

// declare a new express app
const app = express()
app.use(bodyParser.json())
app.use(awsServerlessExpressMiddleware.eventContext())

// Enable CORS for all methods
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "*")
  next()
});

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient();

function id() {
  return Math.random().toString(36).substring(2) + Date.now().toString(36)
}

/****************************
* Example post method *
****************************/

app.post('/orders', function (req, res) {
  const params = {
    TableName: process.env.STORAGE_MYORDERSDB_NAME,
    Item: {
      orderId: id(),
      custId: req.body.custId,
      custName: req.body.custName,
      custPhone: req.body.custPhone,
      paymentMode: req.body.paymentMode,
      cart: req.body.cart,
      address: req.body.address,
      paymentId: req.body.paymentId
    }
  };

  dynamodb.put(params, function (err, data) {
    if (err) {
      res.json({ err });
    } else {
      res.json({ success: "Successfully Created" });
    }
  });
});

/****************************
* Example get method *
****************************/

app.get('/orders', function (req, res) {
  const params = {
    TableName: process.env.STORAGE_MYORDERSDB_NAME
  };

  dynamodb.scan(params, function (err, data) {
    if (err) {
      res.status(500).json({ message: 'Failed to retrieve contacts' });
    } else {
      res.json(data.Items);
    }
  });
});

app.listen(3000, function() {
    console.log("App started")
});

// Export the app object. When executing the application local this does nothing. However,
// to port it to AWS Lambda we will create a wrapper around that will load the app from
// this file
module.exports = app

Log output

``` // Put your logs below this line (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Extended Request Id: FOjNQEjfBcwFtAg= -- (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Verifying Usage Plan for request: 0c1c44e1-1d54-42d8-ba45-cee2037fb46f. API Key: API Stage: scfgj20u1k/dev (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) API Key authorized because method 'ANY /orders' does not require API Key. Request will not contribute to throttle or quota limits (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Usage Plan check succeeded for API Key and API Stage scfgj20u1k/dev (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Starting execution for request: 0c1c44e1-1d54-42d8-ba45-cee2037fb46f (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) HTTP Method: GET, Resource Path: /orders (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Method request path: {} (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Method request query string: {} (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Method request headers: {sec-fetch-site=none, CloudFront-Viewer-Country=IN, CloudFront-Forwarded-Proto=https, CloudFront-Is-Tablet-Viewer=false, User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36, Accept-Encoding=gzip, deflate, br, sec-fetch-user=?1, sec-ch-ua-mobile=?0, upgrade-insecure-requests=1, X-Amz-Cf-Id=NvM3996ndKAyZAA4gfKsPD22Wu98BhbRKXxMuJe0WXnZT7kWMt8ABQ==, CloudFront-Viewer-ASN=132559, CloudFront-Is-Desktop-Viewer=true, Cookie=AMCV_7742037254C95E840A4C98A6%40AdobeOrg=1585540135%7CMCIDTS%7C19435%7CMCMID%7C71041642220953203007104081283546081149%7CMCAID%7CNONE%7CMCOPTOUT-1679171440s%7CNONE%7CvVersion%7C4.4.0, sec-fetch-mode=navigate, Accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7, CloudFront-Is-Mobile-Viewer=false, X-Forwarded-Proto=https, CloudFront-Is-SmartTV-Viewer=false, Host=scfgj20u1k.execute-api.ap-south-1.amazonaws.com, X-Forwa [TRUNCATED] (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Method request body before transformations: (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Endpoint request URI: https://lambda.ap-south-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:ap-south-1:954138568328:function:myordersdb-dev/invocations (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Endpoint request headers: {X-Amz-Date=20230520T152143Z, x-amzn-apigateway-api-id=scfgj20u1k, Accept=application/json, User-Agent=AmazonAPIGateway_scfgj20u1k, Host=lambda.ap-south-1.amazonaws.com, X-Amz-Content-Sha256=eaf34016f604862ddcd1e1b4d3b7dc052d68a7a9edb3dfb38a462e3ed1403f10, X-Amzn-Trace-Id=Root=1-6468e587-286883c3055861c71706c89a, x-amzn-lambda-integration-tag=0c1c44e1-1d54-42d8-ba45-cee2037fb46f, Authorization=**********************************************************************************************************************************************************************************************************************************************************************************************************************************************946391, X-Amz-Source-Arn=arn:aws:execute-api:ap-south-1:954138568328:scfgj20u1k/dev/ANY/orders, X-Amz-Security-Token=IQoJb3JpZ2luX2VjEGcaCmFwLXNvdXRoLTEiSDBGAiEAuGAQ6QypDB7B3qGUR+xRUHG7WzqmODcjNFF5auU6kdACIQCSvc+t7p3AUgbVHpXHTDkXc2vEe5tNTFYtBTkcHzpqNSq9BQiP////////// [TRUNCATED] (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Endpoint request body after transformations: {"resource":"/orders","path":"/orders","httpMethod":"GET","headers":{"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7","Accept-Encoding":"gzip, deflate, br","Accept-Language":"en-US,en;q=0.9,hi;q=0.8,ro;q=0.7","CloudFront-Forwarded-Proto":"https","CloudFront-Is-Desktop-Viewer":"true","CloudFront-Is-Mobile-Viewer":"false","CloudFront-Is-SmartTV-Viewer":"false","CloudFront-Is-Tablet-Viewer":"false","CloudFront-Viewer-ASN":"132559","CloudFront-Viewer-Country":"IN","Cookie":"AMCV_7742037254C95E840A4C98A6%40AdobeOrg=1585540135%7CMCIDTS%7C19435%7CMCMID%7C71041642220953203007104081283546081149%7CMCAID%7CNONE%7CMCOPTOUT-1679171440s%7CNONE%7CvVersion%7C4.4.0","Host":"scfgj20u1k.execute-api.ap-south-1.amazonaws.com","sec-ch-ua":"\"Google Chrome\";v=\"113\", \"Chromium\";v=\"113\", \"Not-A.Brand\";v=\"24\"","sec-ch-ua-mobile":"?0","sec-ch-ua-platform":"\"Windows\"","sec-fetch-dest [TRUNCATED] (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Sending request to https://lambda.ap-south-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:ap-south-1:954138568328:function:myordersdb-dev/invocations (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Received response. Status: 200, Integration latency: 3634 ms (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Endpoint response headers: {Date=Sat, 20 May 2023 15:21:47 GMT, Content-Type=application/json, Content-Length=606, Connection=keep-alive, x-amzn-RequestId=441e966f-f6ab-47a4-aa28-54161c583ffe, X-Amz-Function-Error=Unhandled, x-amzn-Remapped-Content-Length=0, X-Amz-Executed-Version=$LATEST, X-Amzn-Trace-Id=root=1-6468e587-286883c3055861c71706c89a;sampled=0;lineage=3eba44d3:0} (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Endpoint response body before transformations: { "errorType": "Runtime.ImportModuleError", "errorMessage": "Error: Cannot find module 'aws-sdk'\nRequire stack:\n- /var/task/app.js\n- /var/task/index.js\n- /var/runtime/index.mjs", "trace": [ "Runtime.ImportModuleError: Error: Cannot find module 'aws-sdk'", "Require stack:", "- /var/task/app.js", "- /var/task/index.js", "- /var/runtime/index.mjs", " at _loadUserApp (file:///var/runtime/index.mjs:997:17)", " at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1032:21)", " at async start (file:///var/runtime/index.mjs:1195:23)", " at async file:///var/runtime/index.mjs:1201:1" ] } (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Lambda execution failed with status 200 due to customer function error: Error: Cannot find module 'aws-sdk'Require stack:- /var/task/app.js- /var/task/index.js- /var/runtime/index.mjs. Lambda request id: 441e966f-f6ab-47a4-aa28-54161c583ffe (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Gateway response type: DEFAULT_5XX with status code: 502 (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Gateway response body: { "message": "Internal server error" } (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Gateway response headers: {Access-Control-Expose-Headers=Date,X-Amzn-ErrorType, Access-Control-Allow-Headers=Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token, Access-Control-Allow-Origin=*, Access-Control-Allow-Methods=DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT, x-amzn-ErrorType=InternalServerErrorException} (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) Method completed with status: 502 (0c1c44e1-1d54-42d8-ba45-cee2037fb46f) AWS Integration Endpoint RequestId : 441e966f-f6ab-47a4-aa28-54161c583ffe ```

aws-exports.js

/* eslint-disable */
// WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten.

const awsmobile = {
    "aws_project_region": "ap-south-1",
    "aws_cognito_identity_pool_id": "ap-south-1:f46056b9-dd88-4d48-9910-f91b7ce76d0a",
    "aws_cognito_region": "ap-south-1",
    "aws_user_pools_id": "ap-south-1_obIso8e2M",
    "aws_user_pools_web_client_id": "60b4o72ojgs75ejdt6h02a35vd",
    "oauth": {},
    "aws_cognito_username_attributes": [],
    "aws_cognito_social_providers": [],
    "aws_cognito_signup_attributes": [
        "EMAIL",
        "NAME",
        "PHONE_NUMBER"
    ],
    "aws_cognito_mfa_configuration": "OFF",
    "aws_cognito_mfa_types": [
        "SMS"
    ],
    "aws_cognito_password_protection_settings": {
        "passwordPolicyMinLength": 8,
        "passwordPolicyCharacters": []
    },
    "aws_cognito_verification_mechanisms": [
        "EMAIL"
    ],
    "aws_dynamodb_all_tables_region": "ap-south-1",
    "aws_dynamodb_table_schemas": [
        {
            "tableName": "myproddb-dev",
            "region": "ap-south-1"
        },
        {
            "tableName": "myordersdb-dev",
            "region": "ap-south-1"
        }
    ],
    "aws_cloud_logic_custom": [
        {
            "name": "myapi",
            "endpoint": "https://scfgj20u1k.execute-api.ap-south-1.amazonaws.com/dev",
            "region": "ap-south-1"
        }
    ]
};

export default awsmobile;

Manual configuration

No response

Additional configuration

No response

Mobile Device

No response

Mobile Operating System

No response

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

No response

chrisbonifacio commented 1 year ago

Hi @xanderbilla 👋 thanks for raising this issue. Which version of node is your lambda running? If 18, I think the version of the aws-sdk (v3) requires that you import scoped packages such as @aws-sdk/lib-dynamodb or @aws-sdk/client-xxx. So I think you might either have to simply change the package you're importing or downgrade your node version to 16 for aws-sdk v2 to be included in the build.

For more information:

https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/#generated-code