How can you use my Api made with FastAPI, from my localhost, from an external html, for example, it is my simple implementation of test:
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>
but the return navigator(Safari) is:
[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
How can you use my Api made with FastAPI, from my localhost, from an external html, for example, it is my simple implementation of test:
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>
but the return navigator(Safari) is:
Share Improve this question edited Nov 13, 2021 at 21:44 user 5,7169 gold badges50 silver badges80 bronze badges asked Sep 20, 2020 at 23:26 Luis RamirezLuis Ramirez 471 gold badge2 silver badges7 bronze badges 3[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
- 1 You need to enable CORS server-side: fastapi.tiangolo./tutorial/cors – user5734311 Commented Sep 20, 2020 at 23:28
-
Origin null is not allowed
- how are you loading the index.html?http://
?file:///
? – Jaromanda X Commented Sep 20, 2020 at 23:30 - loaded in 127.0.0.1:5500/index.html – Luis Ramirez Commented Sep 21, 2020 at 1:24
1 Answer
Reset to default 6You have to enable CORS in your API:
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"}
See more information about CORS here.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742255636a4409968.html
评论列表(0条)