You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Lambda公共URL访问显示空白页如何解决

问题现象
  • 通过公共URL调用Lambda函数时,页面无任何输出、显示空白
  • 在AWS控制台内直接测试函数,可以正常得到预期输出
  • 函数URL配置路径:Configuration -> Function URL -> Create Function Url,认证类型选择None,开启CORS并使用默认配置

原函数代码如下:

# Lambda function
import json
import hmac, base64, struct, hashlib, time

sec = 'my_secret'

def get_hotp_token(secret, intervals_no):
    key = base64.b32decode(secret, True)
    msg = struct.pack(">Q", intervals_no)
    h = hmac.new(key, msg, hashlib.sha1).digest()
    o = h[19] & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return h

def get_totp_token(secret):
    return get_hotp_token(secret, intervals_no=int(time.time())//30)


def lambda_handler(event, totp):
    # totp = get_totp_token(sec)
    # print(totp)
    return {
        'statusCode' : 200,
        'totp' : get_totp_token(sec)
    }
故障原因

Lambda Function URL 遵循和API Gateway代理集成一致的响应格式规范,当前返回结构不符合要求:

  1. 缺少必填的body字段,所有返回给客户端的内容必须放在该字段中,且需要序列化为字符串格式
  2. 缺少headers字段声明响应内容类型,浏览器无法识别返回内容,直接渲染为空白页
  3. 额外的totp字段直接放在返回结构顶层,不会被服务端透传给客户端

注:lambda_handler的第二个参数为运行时上下文对象,命名为totp不会直接导致报错,但不符合开发规范,后续如果需要调用上下文方法会出现异常。

修复方法

调整Lambda函数的返回结构,补全规范要求的字段即可,修改后的代码如下:

import json
import hmac, base64, struct, hashlib, time

sec = 'my_secret'

def get_hotp_token(secret, intervals_no):
    key = base64.b32decode(secret, True)
    msg = struct.pack(">Q", intervals_no)
    h = hmac.new(key, msg, hashlib.sha1).digest()
    o = h[19] & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return h

def get_totp_token(secret):
    return get_hotp_token(secret, intervals_no=int(time.time())//30)


def lambda_handler(event, context):
    totp_code = get_totp_token(sec)
    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'application/json'
        },
        'body': json.dumps({
            'totp': totp_code
        })
    }

如果需要浏览器直接展示纯文本的TOTP码,不需要JSON格式,可以把返回部分替换为:

return {
    'statusCode': 200,
    'headers': {
        'Content-Type': 'text/plain'
    },
    'body': str(get_totp_token(sec))
}

部署修改后的代码,再访问函数URL即可正常看到返回内容。

内容的提问来源于stack exchange,提问作者Sid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 03:00:24