javascript - 在 localhost 中为 FastApi 获取 JavaScript
问题描述
你如何使用我用 FastAPI 制作的 Api,来自我的本地主机,来自外部 html,例如,这是我对测试的简单实现:
主要.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def main():
return {"message": "Hello World"}
索引.html:
<html>
<head>
<title>Item Details</title>
</head>
<body>
<script>
//var url = 'http://localhost:8000';
fetch('http://127.0.0.1:8000/')
.then(res => res.json())
.then(data => {console.log(data)})
</script>
<h1></h1>
</body>
</html>
但返回导航器(Safari)是:
[错误] Access-Control-Allow-Origin 不允许 Origin null。[错误]由于访问控制检查,Fetch API 无法加载http://127.0.0.1:8000/ 。[错误] 加载资源失败:Access-Control-Allow-Origin 不允许 Origin null。(127.0.0.1,第 0 行)[错误] 未处理的承诺拒绝:TypeError:Access-Control-Allow-Origin 不允许 Origin null。(匿名函数)promiseReactionJob
解决方案
您必须在 API 中启用 CORS:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:8000"
"http://localhost:8080",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def main():
return {"message": "Hello World"}
在此处查看有关 CORS 的更多信息。
推荐阅读
- android - 为什么 ImageView 不显示在 Activity Android Studio 中
- python - TransformedTargetRegressor 保存和加载错误
- icons - 如何使用 KaiOS 动作图标?
- jhipster - JHipster 在构建时测试问题
- c# - 无法在列表 c# 中保存通用接口实现
- swift - 摆脱标签视图中的导航栏
- macos - Selenium Chrome 驱动程序在 macOS 上崩溃
- joomla3.0 - 如何将子表单的(Joomla)管理布局从表格模式更改为 div 模式?
- django - 写入文件,然后通过 api 发送
- android - Android以编程方式执行shell命令(非root)