Search code examples
javascriptamazon-web-serviceshttp-redirectaws-lambdagateway

How can I redirect a URL for post request using AWS lambda?


These results are for GET and POST requests response through API gateway and lambda. used same lambda function, but when i used post method of API gateway, response just shows me JSON. what should i have to do?

when i used post req

when i used get req it's my lambda function

exports.handler = (event, context, callback) => {
   const response = {
    statusCode: 301,
    headers: {
      Location: 'https://google.com',
    }
  };

  return callback(null, response);
}

thank you.


Solution

  • I usually use the new async/await pattern when defining my aws lambdas :

    exports.handler = async (event) => {
     // do stuff...
    }
    

    you usually don't need the context, unless you want to use some aws-related info regarding your lambda. I have a helper function that is re-used a lot inside the code base

    function proxyResponse(inBody, inStatusCode = null, headers = {}, event = null) {
      if (!isApiGateway(event)) {
        if (inBody instanceof Error) {
          throw inBody;
        }
        return inBody;
      }
      let statusCode = inStatusCode;
    
      let body;
      if (inBody instanceof Error) {
        statusCode = statusCode || INTERNAL_SERVER_ERROR;
        body = JSON.stringify({
          message: inBody.message,
          code: statusCode,
        });
      } else if (inBody instanceof Object) {
        body = JSON.stringify(inBody);
      } else {
        body = inBody;
      }
    
      const [origin] = event ? caseHandler(event.headers, 'origin') : [];
    
      return {
        statusCode: statusCode || 200,
        body,
        headers: Object.assign({
          'Access-Control-Allow-Headers': 'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token,x-api-key,Authorization',
          'Access-Control-Allow-Origin': origin,
          'Access-Control-Allow-Credentials': true,
          'Access-Control-Allow-Methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT',
        }, headers),
      };
    }
    

    and another one :

    function caseHandler(mixedCaseObject, inputKey) {
      if (!mixedCaseObject || !inputKey) {
        return [];
      }
      return Object.keys(mixedCaseObject)
        .filter((key => key.toLowerCase() === inputKey.toLowerCase()))
        .map(key => mixedCaseObject[key]);
    }
    

    and this one :

    function isApiGateway(event) {
      return (!!event.httpMethod && !!event.headers && !!event.requestContext);
    }
    

    so inside the lambda whenever I want to return something I use this helper functions :

    module.exports.handler = async (event) => {
      try{
     // do stuff...
     return proxyResponse(YOUR_CUSTOM_BODY_OBJECT, Api.HTTP.OK, {}, event);
     } catch(error) {
     return proxyResponse(error, Api.HTTP.INTERNAL_SERVER_ERROR, {}, event);
     }
    }