2

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

3
  • 1
    You need to enable CORS server-side: fastapi.tiangolo.com/tutorial/cors Commented Sep 20, 2020 at 23:28
  • Origin null is not allowed - how are you loading the index.html? http://? file:///? Commented Sep 20, 2020 at 23:30
  • loaded in 127.0.0.1:5500/index.html Commented Sep 21, 2020 at 1:24

1 Answer 1

6

You 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Access to fetch at '127.0.0.1:8000' from origin '127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.