你如何使用我用 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/