如何解决在localhost
如何使用我的本地主机,外部html中的FastAPI制作的Api,例如,这是我对test的简单实现:
main.py: 从fastapi导入FastAPI
app = FastAPI()
@app.get("/")
async def main():
return {"message": "Hello World"}
index.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。 [错误]由于访问控制检查,提取API无法加载http://127.0.0.1:8000/。 [错误]无法加载资源:Access-Control-Allow-Origin不允许使用Origin null。 (127.0.0.1,第0行) [错误]未处理的承诺拒绝:类型错误: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 here的更多信息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。