0

attempting to learn aws lambda and api gateway. Attempting to recreate http://checkip.amazonaws.com/ (returns client's public IP).

I found - How can I retrieve a user's public IP address via Amazon API Gateway + Lambda (node) .

It says - API Mapping template:

{
    "sourceIP" : "$context.identity.sourceIp"
}

Lambda function:

'use strict';
console.log('Loading function');
exports.handler = (event, context, callback) => {
    console.log('SourceIP =', event.identity.sourceIP);
    callback(null, event.identity.sourceIP);
};

Not sure what I'm doing incorrectly. In AWS console, I - select "create function" select "author from scratch" Enter my function's name and choose Node.js 14.X runtime. I click on "create function" and add the function code.

I then - Navigate to api gateway click on "build" under "Rest API" I select "New API" I name it, give it a description and slick on "create api" I create the "Get" method with lambda integration type, select the lambda I created earlier, and click "Save". I then click on the "Integration Request", select "Mapping Templates", add application/json as the content type, and the mapping template.

after saving, I deploy the API. When I try a "Get" on the invoke URL, the response I get is -

{
    "errorType": "TypeError",
    "errorMessage": "Cannot read property 'sourceIP' of undefined",
    "trace": [
        "TypeError: Cannot read property 'sourceIP' of undefined",
        "    at Runtime.exports.handler (/var/task/index.js:4:46)",
        "    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
    ]
}

Thanks for any help in resolving this error or clearly explaining / showing screenshots of any better ways to achieve this.

Thanks!

kpg11
  • 11
  • 2
  • 1
    The source IP is under `event.requestContext.identity.sourceIp` for v1 of the API Gateway interface, and `event.requestContext.http.sourceIp` for v2. See the [documentation](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html) – Anon Coward Jun 02 '22 at 20:35
  • 1
    You can also simply console.log the `event` and `context` parameters to review what's contained in them. – jarmod Jun 02 '22 at 21:00
  • Thanks for your response. Not familiar with how to do this, but will research it. – kpg11 Jun 02 '22 at 21:09
  • console.log(event/context); – Riz Jun 02 '22 at 23:41

0 Answers0