Error when trying to use lambda to return client IP

0

Hello. Attempting to create something similar to http://checkip.amazonaws.com/ . Am open to other solutions, but the one I found is https://stackoverflow.com/questions/33062097/how-can-i-retrieve-a-users-public-ip-address-via-amazon-api-gateway-lambda-n .

When I use this for the lambda function -

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

and this for the mapping template -

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

I get this error -

{ "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)" ] }

Can someone please walk me through the steps to correctly implement the lambda function and mapping template above or perhaps if you have a better method to return the client IP of a simple get request, please share?

Thank you

  • Can you log the "event" parameter? I think you should use "event.sourceIP"

1 Antwort
1
Akzeptierte Antwort

It depends on which API you are using. If you are using HTTP API, the source IP is at event.requestContext.http.sourceIP or event.headers.x-forwarded-for. If you are using REST API it will be in event.headers.X-Forwarded-For or event.requestContext.identity.sourceIp. You are trying to access event.identity.sourceIP.

Note, in both cases you do not need a mapping template, just return a body from the Lambda function. If you are using REST API, you may be able to implement it using a Mock integration and a mapping template, although I did not test it.

profile pictureAWS
EXPERTE
Uri
beantwortet vor 2 Jahren
profile pictureAWS
EXPERTE
Toni_S
überprüft vor 2 Jahren

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen