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

AWS API网关Stage Name在表单提交时丢失的原因排查

问题描述

在AWS Lambda上基于Flask搭建的简易网站中,使用以下表单提交文件:

<form action="/upload" method="post" enctype="multipart/form-data">
  <div class="form-group">
    <label for="file">Upload Document:</label>
    <input type="file" id="file" name="file" accept=".docx" required>
  </div>
  <div class="form-group">
    <label for="email">Email Address:</label>
    <input type="email" class="form-control" id="email" name="email"
    placeholder="Enter your email address" required>
  </div>
  <button type="submit" class="btn btn-primary">Send for Review</button>
</form>

预期表单提交后指向路径:https://abcd1234.execute-api.ap-south-1.amazonaws.com/v0/upload,但实际提交路径为:https://abcd1234.execute-api.ap-south-1.amazonaws.com/upload,缺失了/v0阶段前缀。

配套的Flask应用代码如下:

from flask import Flask, render_template, request
import awsgi

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload():
    return

def lambda_handler(event, context):
    return awsgi.response(app, event, context, base64_content_types={"image/png"})

if __name__ == '__main__':
    app.run(debug=True)
问题原因及解决办法

原因

  1. 浏览器相对路径解析规则:API Gateway部署了v0阶段,页面加载路径为https://abcd1234.execute-api.ap-south-1.amazonaws.com/v0/,表单使用相对路径/upload时,浏览器会去掉当前URL最后一个路径段(v0/),拼接为根目录下的/upload,导致缺失阶段前缀。
  2. Flask未适配阶段前缀:Flask应用默认根路径为/,未配置API Gateway的v0阶段前缀,因此生成的路由路径不会自动带上该前缀。

解决办法

方法1:直接修改表单action路径

将表单的action属性改为包含阶段前缀的路径:

<form action="/v0/upload" method="post" enctype="multipart/form-data">
  <!-- 表单内容保持不变 -->
</form>

方法2:配置Flask根路径并动态生成路径

通过Flask配置适配阶段前缀,再用url_for动态生成提交路径,避免硬编码:

  1. 修改Flask初始化代码:
app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/v0'
  1. 模板中使用url_for生成表单action:
<form action="{{ url_for('upload') }}" method="post" enctype="multipart/form-data">
  <!-- 表单内容保持不变 -->
</form>

后续阶段前缀变更时,只需修改Flask配置即可,无需逐一调整模板路径。

方法3:API Gateway路径重写(可选)

若不想修改代码,可在API Gateway的集成请求中设置路径重写,将/upload映射为/v0/upload,但这种方式不够直观,优先推荐前两种方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 22:47:20