you can find answer from this:fastapi cors
then this is a very simple code to achieve it:
-
create a python file and named it
main.py. -
add code in this file.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def main():
return {"message": "Hello World"}
and run this app:
uvicorn main:app --reload --host 0.0.0.0 --port 8000
if you computer ip is 192.12.12.12
you can check this link and just write a small javascript in html:
<script>
fetch("http://192.12.12.12:8000/").then((Response) => {
return Response.json()
}).then((data) => {
console.log(data);
})
</script>