javascript - 在本地主机中获取 FastApi 的 JavaScript

标签 javascript python fastapi

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

主要.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>

但返回导航器(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 .

关于javascript - 在本地主机中获取 FastApi 的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63984555/

相关文章:

javascript - 单击新窗口中的链接打开新页面

python - 如何从对象访问值

python - 如何在 Debug模式下运行fastapi项目在vscode中自动重新加载

python - python 中的 Split() 如果有条件必须跳过某些值,如何使用

python - 如何使用 FastAPI 上传文件和 JSON 数据?

Javascript 函数仅适用于第一个 FORM

javascript - 如何使用 Chart.js 在标签中放置新行?

javascript - 带有 jQ​​uery 的 fancybox v2

python - 如何删除 pandas 中给定行中仅包含零的列