不同目录下HTML表单调用FastAPI POST接口失效问题咨询
问题解决方法
1. 修正接口地址匹配错误
FastAPI的路由是服务层定义的逻辑路径,和本地文件的物理目录完全没有关联,不要尝试用文件路径作为接口地址。你之前填写目录路径的做法完全错误,接口地址仅和你FastAPI服务的启动地址、路由定义有关,你定义的/uploadImages路由,对应的完整接口地址为 http://<FastAPI服务IP>:<服务端口>/uploadImages,默认启动下地址为 http://127.0.0.1:8000/uploadImages。
分两种场景配置:
- 如果你直接双击打开本地的index.html(用
file://协议访问):- 表单的action属性填完整的接口地址:
http://127.0.0.1:8000/uploadImages - 在FastAPI中添加跨域中间件,允许本地文件的跨域请求,补充代码如下:
- 表单的action属性填完整的接口地址:
from fastapi.middleware.cors import CORSMiddleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # 开发环境临时使用,生产环境请替换为实际允许的域名 allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
- 推荐方案:让FastAPI直接托管静态文件,统一入口:
在main.py中补充静态文件挂载和首页路由的代码:
from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse import os # 挂载assets静态资源目录 app.mount("/assets", StaticFiles(directory=os.path.join(os.path.dirname(__file__), "../assets")), name="assets") # 首页路由返回根目录的index.html @app.get("/") async def get_index_page(): return FileResponse(os.path.join(os.path.dirname(__file__), "../index.html"))
配置完成后直接访问http://127.0.0.1:8000打开页面,表单的action属性直接填/uploadImages即可正常访问接口。
2. 实现无刷新提交,将返回值填入textarea
默认的表单提交行为会跳转页面,要在当前页面展示返回结果,需要用JS拦截表单的默认提交行为,通过Fetch API发送请求,把返回结果写入textarea即可。在index.html的</body>前添加如下代码:
<script> const uploadForm = document.getElementById('uploadform'); const resultTextarea = document.querySelector('textarea'); uploadForm.addEventListener('submit', async function(e) { // 阻止默认的表单跳转行为 e.preventDefault(); // 构造表单数据对象 const formData = new FormData(uploadForm); try { const response = await fetch('/uploadImages', { method: 'POST', body: formData }); // 读取接口返回的文本内容 const result = await response.text(); // 写入textarea resultTextarea.value = result; } catch (error) { resultTextarea.value = '请求失败:' + error.message; } }) </script>
配置完成后提交表单就不会跳转,返回结果会直接显示在textarea中。
内容的提问来源于stack exchange,提问作者Mc Midas
相关产品推荐
相关产品推荐

