首页 > 解决方案 > 在 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

标签: javascriptpythonfastapi

解决方案


您必须在 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 的更多信息。


推荐阅读