在本地主机中获取 FastApi 的 JavaScript

Fetch in JavaScript for FastApi in localhost

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

main.py:

from fastapi import 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>

但是 return 导航器 (Safari) 是:

[Error] Origin null is not allowed by Access-Control-Allow-Origin. [Error] Fetch API cannot load http://127.0.0.1:8000/ due to access control checks. [Error] Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin. (127.0.0.1, line 0) [Error] Unhandled Promise Rejection: TypeError: Origin null is not allowed by Access-Control-Allow-Origin. (anonymous function) 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