为什么我的AWS Lambda函数中event.requestContext为未定义?

huangapple go评论76阅读模式
英文:

Why is event.requestContext undefined for my AWS Lambda function?

问题

为什么我无法获取用户的远程IP地址?

当我点击测试按钮或功能URL时,似乎event.requestContext未定义。为什么?

const res = { 
    statusCode: 200,
    isBase64Encoded: false,
    headers: { 
        "Access-Control-Allow-Origin":"*",
        "Content-Type": "text/plain" 
    },
    multiValueHeader: {}
};

export const handler = async(event) => {
    const ip = event.requestContext.identity.sourceIp;
    res.body="hi "+ip; 
    return res;
}
英文:

Why was I unable to obtain the remote IP address of the user?

When I clicked on the test button or the function URL, it seems that event.requestContext was undefined. Why?

const res = { 
    statusCode: 200,
    isBase64Encoded: false,
    headers: { 
        "Access-Control-Allow-Origin":"*",
        "Content-Type": "text/plain" 
    },
    multiValueHeader: {}
};

export const handler = async(event) => {
    const ip = event.requestContext.identity.sourceIp;
    res.body="hi "+ip; 
    return res;
}

答案1

得分: 0

似乎事件格式不正确。这个部分是正确的:

const ip = event.requestContext.http.sourceIp;

我之前使用的是Lambda版本1的格式,但现在我正在使用版本2。

英文:

It seems that the event format is incorrect. This works:

const ip = event.requestContext.http.sourceIp;

What I used was the format for Lambda version 1 but I am now using version 2.

huangapple
  • 本文由 发表于 2023年1月7日 16:18:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75038971.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定