Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SyntaxError: Unexpected token '.' #3361

Closed
faridg18 opened this issue Oct 13, 2021 · 5 comments
Closed

SyntaxError: Unexpected token '.' #3361

faridg18 opened this issue Oct 13, 2021 · 5 comments
Labels
blocked/close-if-inactive Blocked for >14 days with no response, will be closed if still inactive after 7 days type/question

Comments

@faridg18
Copy link

Description:

I am having problems trying to run my lambda project, I keep getting unexpected token on the response.

Steps to reproduce:

Observed result:

I am trying to run lambda functions on my local machine. I am using

sam local start-api

the project compiles and runs but whenever I make a call to any route I get the following error:

Lambda returned empty body!
Invalid lambda response received: Invalid API Gateway Response Keys: {'errorType', 'errorMessage'} in {'errorType': 'Runtime.UserCodeSyntaxError', 'errorMessage': "SyntaxError: Unexpected token '.'"}

Also when I try to run sam validate

 sam validate

I get the following error, I don't know if it is related.

botocore.exceptions.ClientError: An error occurred (SignatureDoesNotMatch) when calling the ListPolicies operation: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

Expected result:

Additional environment details (Ex: Windows, Mac, Amazon Linux etc)

  1. OS:
    Mac OS
  2. sam --version:
    SAM CLI, version 1.12.0
  3. AWS region:
    us-east-1

Add --debug flag to command you are running

@hawflau hawflau added blocked/more-info-needed More info is needed from the requester. If no response in 14 days, it will become stale. stage/bug-repro The issue/bug needs to be reproduced labels Oct 14, 2021
@hawflau
Copy link
Contributor

hawflau commented Oct 14, 2021

Hey @faridg18 can you please provide your template and also your Lambda function code?
I tried what you did with a nodejs14.x hello world template and it worked fine. The SyntaxError: Unexpected token '.' error message suggests there could be syntax error in your Lambda code. It'll helpful if we can look into it.

Also, you mentioned you are using SAM CLI version 1.12.0, which is quite old. Is there any reason you are still using the old version? I'd encourage you to upgrade to our latest version (v1.33.0).

@faridg18
Copy link
Author

faridg18 commented Oct 14, 2021

I just installed the sam with python, didn't check for version. Here is a strip down version of my code with the function that I am trying to run.

My Template

AWSTemplateFormatVersion: 2010-09-09
Description: >-
   backend

Transform:
- AWS::Serverless-2016-10-31

Globals:
  Function:
    Runtime: nodejs12.x
    Timeout: 600
    Handler: index.handler
    Environment:
      Variables:

Resources:
  authFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/auth.authHandler
      Runtime: nodejs12.x
      MemorySize: 3072
      Timeout: 600
      Description: A Lambda function that returns a static string.
      Policies:
        - AWSLambdaBasicExecutionRole
        
      Events:
        Login:
          Type: Api 
          Properties:
            Path: /user/login
            Method: post

        Register:
          Type: Api 
          Properties:
            Path: /user/signup
            Method: post  

        Activation:
          Type: Api 
          Properties:
            Path: /user/activation
            Method: post

        ResendOtp:
          Type: Api
          Properties:
            Path: '/user/resend-otp'
            Method: post      

        ForgotPassword:
          Type: Api 
          Properties:
            Path: /user/forgot-password
            Method: post

        Verification:
          Type: Api 
          Properties:
            Path: /user/verification
            Method: post    

        ChangePassword:
          Type: Api 
          Properties:
            Path: /user/change-password
            Method: post

        UserDetails:
          Type: Api 
          Properties:
            Path: /user/details
            Method: get

        Logout:
          Type: Api 
          Properties:
            Path: /user/logout
            Method: get

        UserLogout:
          Type: Api 
          Properties:
            Path: /user/logout
            Method: post    

        SetPassword:
          Type: Api 
          Properties:
            Path: /user/set-password
            Method: post
        UpgradeToPro:
          Type: Api 
          Properties:
            Path: /user/upgrade-to-pro
            Method: post
        AddCreditCard:
          Type: Api 
          Properties:
            Path: /user/add-credit-card
            Method: post
        UpdateCreditCard:
          Type: Api 
          Properties:
            Path: /user/update-credit-card
            Method: post    
        DeleteCreditCard:
          Type: Api 
          Properties:
            Path: /user/delete-credit-card
            Method: post    
        SetDefaultCard:
          Type: Api 
          Properties:
            Path: /user/set-default-card
            Method: post
        StripeUserDetail:
          Type: Api 
          Properties:
            Path: /user/stripe-user-details
            Method: post
        StripeCreateCharge:
          Type: Api 
          Properties:
            Path: /user/add-credit
            Method: post
        AddToWallet:
          Type: Api 
          Properties:
            Path: /user/add-to-wallet
            Method: post
        TransferToPro:
          Type: Api 
          Properties:
            Path: /user/transfer-to-pro
            Method: post
        WalletDeduction:
          Type: Api 
          Properties:
            Path: /user/wallet-deduction
            Method: post  
        CallHistory:
          Type: Api 
          Properties:
            Path: /user/call-history
            Method: post    
        CreateStripeAccountLink:
          Type: Api 
          Properties:
            Path: /user/stripe-account-link
            Method: get    
        StripeVerificationSuccess:
          Type: Api 
          Properties:
            Path: /user/stripe-verification-success
            Method: get

My lambda Function

For now I am only trying to run the login function:

api.post("/user/login", async (req, res) => {
  console.log("logging in");

  let reqData = req.body;
  if (!validator.isEmail(reqData.email)) {
    return commonFunc.errorRes(res, 400, "Invalid email address.");
  }
  try {
    let user = await UserModel.findOne({
      email: reqData.email,
      isBlocked: false,
      isDeleted: false,
    });
    if (user && user?.verified) {
      const match = await argon2.verify(user.password, reqData.password);
      if (!match) {
        res.status(400).send({ error: "The password is invalid." });
        return;
      }
      await UserModel.update(
        { _id: user._id },
        { $addToSet: { deviceID: reqData.deviceID } }
      );
      return {
        message: "Successfully logged in.",
        data: commonFunc.resData(user),
      };
    } else if (user && !user?.verified) {
      let verifyCode = Math.floor(Math.random() * 8999 + 1000).toString();
      user.verificationCode = AES.encrypt(
        verifyCode,
        variables.SECRET_SALT
      ).toString();
      user.verificationExpiredOn = datefns.addHours(new Date(), 1);
      await user.save();
      res.status(554).send({
        message: "OTP successfully sent.",
        data: { id: user._id, verified: user.verified },
      });
      return;
    } else {
      res.status(404).send({
        error: "There is no user record corresponding to this identifier.",
      });
      return;
    }
  } catch (e) {
    res.status(500).send({ error: "Something wrong!" });
    return;
  }
});

module.exports.authHandler = async (event, context) => {
  context.callbackWaitsForEmptyEventLoop = false;
  await dbConnect();

  return await api.run(event, context);
};

@faridg18
Copy link
Author

Also even though if I reduce the login function to

api.post("/user/login", async (req, res) => {
  return 'hello';
});

I still get the same error

2021-10-14T17:41:26.853Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Unexpected token '.'","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Unexpected token '.'","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
START RequestId: 1a1170aa-e156-11fd-c484-6515e63776ea Version: $LATEST
END RequestId: 1a1170aa-e156-11fd-c484-6515e63776ea
REPORT RequestId: 1a1170aa-e156-11fd-c484-6515e63776ea	Init Duration: 275.51 ms	Duration: 1.70 ms	Billed Duration: 100 ms	Memory Size: 3072 MB	Max Memory Used: 41 MB	
2021-10-14 11:41:26,977 | Lambda returned empty body!
2021-10-14 11:41:26,977 | Invalid lambda response received: Invalid API Gateway Response Keys: {'errorType', 'errorMessage'} in {'errorType': 'Runtime.UserCodeSyntaxError', 'errorMessage': "SyntaxError: Unexpected token '.'"}

@faridg18
Copy link
Author

faridg18 commented Oct 14, 2021

after updating sam cli I get the following error code "InvokeID= error="Runtime exited with error: exit status 129"

2021-10-14 12:11:16,662 | Unable to find Click Context for getting session_id.
2021-10-14 12:11:16,662 | Lambda returned empty body!
2021-10-14 12:11:16,662 | Invalid lambda response received: Invalid API Gateway Response Keys: {'errorType', 'trace', 'errorMessage'} in {'errorType': 'Error', 'errorMessage': '/var/task/node_modules/argon2/lib/binding/napi-v3/argon2.node: invalid ELF header', 'trace': ['Error: /var/task/node_modules/argon2/lib/binding/napi-v3/argon2.node: invalid ELF header', '    at Object.Module._extensions..node (internal/modules/cjs/loader.js:1131:18)', '    at Module.load (internal/modules/cjs/loader.js:937:32)', '    at Function.Module._load (internal/modules/cjs/loader.js:778:12)', '    at Module.require (internal/modules/cjs/loader.js:961:19)', '    at require (internal/modules/cjs/helpers.js:92:18)', '    at Object.<anonymous> (/var/task/node_modules/argon2/argon2.js:9:56)', '    at Module._compile (internal/modules/cjs/loader.js:1072:14)', '    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)', '    at Module.load (internal/modules/cjs/loader.js:937:32)', '    at Function.Module._load (internal/modules/cjs/loader.js:778:12)', '    at Module.require (internal/modules/cjs/loader.js:961:19)', '    at require (internal/modules/cjs/helpers.js:92:18)', '    at Object.<anonymous> (/var/task/src/handlers/auth.js:5:16)', '    at Module._compile (internal/modules/cjs/loader.js:1072:14)', '    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)', '    at Module.load (internal/modules/cjs/loader.js:937:32)']}

@hawflau hawflau removed the blocked/more-info-needed More info is needed from the requester. If no response in 14 days, it will become stale. label Oct 16, 2021
@hawflau
Copy link
Contributor

hawflau commented Oct 16, 2021

Thanks for providing more info. The api in your code seems to be an express.js app.

While I'm not sure what api.run(event, context) returns, API Gateway or the local api started by sam local start-api is expecting the lambda to return an output of the following format:

{
  "isBase64Encoded" : "boolean",
  "statusCode": "number",
  "headers": { ... },
  "body": "JSON string"
}

(See here for more info)

For example, I created a lambda handler which returns a response not conforming to what API Gateway expects:

exports.lambdaHandler = async (event, context) => {
    return {
        "message": "123",
        "data": '123',
    };
};

And from sam local start-api, I saw this when I call the api:

START RequestId: ec3c4c01-9099-4865-b638-7ad79d5f5f6d Version: $LATEST
END RequestId: ec3c4c01-9099-4865-b638-7ad79d5f5f6d
REPORT RequestId: ec3c4c01-9099-4865-b638-7ad79d5f5f6d  Init Duration: 0.18 ms  Duration: 153.41 ms     Billed Duration: 154 ms Memory Size: 128 MB     Max Memory Used: 128 MB
Lambda returned empty body!
Invalid lambda response received: Invalid API Gateway Response Keys: {'message', 'data'} in {'message': '123', 'data': '123'}

It doesn't seem like there's any issue within sam local start-api causing the output you saw. I'd suggest you look into what app.run(event, context) resolves to return.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
blocked/close-if-inactive Blocked for >14 days with no response, will be closed if still inactive after 7 days type/question
Projects
None yet
Development

No branches or pull requests

4 participants