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개 답변
1
수락된 답변

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
전문가
Uri
답변함 2년 전
profile pictureAWS
전문가
Toni_S
검토됨 2년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠