在localhost中获取FastApi的JavaScript

2024-05-18 07:33:47 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用FastAPI制作的Api,从我的本地主机,从外部html,例如,这是我的简单测试实现:

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)是: [错误]访问控制允许原点不允许原点为空。 [错误]由于访问控制检查,获取API无法加载http://127.0.0.1:8000/。 [错误]加载资源失败:访问控制不允许原点为null允许原点。(127.0.0.1,第0行) [错误]未处理的承诺拒绝:TypeError:Origin null不被访问控制允许Origin。 (匿名函数) 激励工作

谢谢你的帮助


Tags: apphttptitlemainhtml错误scriptbody
1条回答
网友
1楼 · 发布于 2024-05-18 07:33:47

您必须在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"}

请参阅有关CORShere的更多信息

相关问题 更多 >