1

i'm writing a serverless node rest api, and i have few functions and today i faced an issue on sending responds from lambda function to api gateway, my callback doesn't work as it expected, what i am doing wrong?

module.exports.create = (event, context, callback) => {

  client.on('connect', () => {
      console.log("connected to redis");
      callback(null, {
        statusCode: 200,
        headers: { 'Content-Type': 'text/plain' },
        body: 'connection established.',
      });
      return;
  });

};

3 Answers 3

1

A common issue people have with Lambda and NodeJS is timing... I think what's happening here is that the Lambda Function terminates before your response comes back. Lambda does not wait around for an async response, so most of the time doesn't execute the responds events, so never hits your callback.

Try using a Promise, which keeps the code/Lambda running until the async call comes back and the callback is called.

This is a good article on how to achieve that:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Sign up to request clarification or add additional context in comments.

Comments

0

Ok, I've encountered Internal server error a few times before and I suggest you to do this.

First, a little background knowledge you must have:

When you're deploying your serverless application, what is happening under the hood is that serverless framework creates necessary configurations and .zip file (your lambda functions code and dependencies) under .serverless folder.

So if you're missing necessary dependencies in your package.json or forget to include them in the .zip file, your lambda will return Internal server error.

And you should check whether you included dependencies into dev-dependencies in package.json, too. (This will prevent your necessary modules to be included in .zip file).

And secondly, if you're using serverless-webpack plugin, you should include these lines in your serverless.yaml file.

custom:
  webpack:
    includeModules: true

This worked for my case.

If you don't understand or have anything to ask, feel free to do that :)

Comments

0

Internal errors are when the return isn't hit for some reason, it can be a coding error or a timeout because the default serverless timeout is too low for what you are trying to do.

If you want to alter the timeout you can do something like this in the serverless.yml:

functions:
  create:
    handler: handler/create
    timeout: 30
    ...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.