Home > Software design >  JavaScript ES6 FastAPI Fetch results in "Type Error"
JavaScript ES6 FastAPI Fetch results in "Type Error"

Time:03-15

i try to set up an simple API on my local machine with FastAPI Backend and then fetch it with a simple JS Script. I googled the whole day, but still can't figure out the issue.

I could bet i missed something.

The FastAPI Backend looks like:

from fastapi import FastAPI
import uvicorn

from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()

origins = [
    "http://localhost",
    "http://localhost:8000",
    "http://127.0.0.2",
    "http://127.0.0.2:8000"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def root():
    return {"Message": "Root"}

    
if __name__ == '__main__':
    uvicorn.run(app, host="127.0.0.2", port="8000")

And Js Script looks like:

async function getRoot() {

fetchAdresse = 'http://127.0.0.2:8000';


const response = await fetch(fetchAdresse, {
    method: 'GET',
    headers: {
        accept: 'html/text',
    },
});

console.log(response);

}

getRoot();

Response is always the same:

Uncaught TypeError TypeError: Failed to fetch

On the other Hand Server response is:

INFO:     127.0.0.1:60927 - "GET / HTTP/1.1" 200 OK

CodePudding user response:

"Failed to fetch" can mean many different things.

I suggest you open up the network tab in inspect mode. It should look like this:Devtools inspect network tab When the program fetches, there should be a request going out, and you should see it there. You can then have a look at the "status", or click on the request for a clearer error and then Google that.

  • Related