1

I am trying to build a data ploting app, when I request data from the javascript to uvicorn server using fastAPI, browser throws CORS error related to headers. I tried to provide headers as given bellow but not sure how to authonticate them at server side using fastAPI.

JavaScript:

  var url = 'http://127.0.0.1:8000/data';

  $.ajax({
  url: url,
  type:'GET',
  dataType: 'json',
  beforeSend: setHeader,
  // data: data,
  success: function(response) {
    chartCircle.updateSeries([
      response.q
    ],
    console.log(response.q)
    )

  }
});


function setHeader(xhr) {
        xhr.setRequestHeader('securityCode', 'Foo');
        xhr.setRequestHeader('passkey', 'Bar');
}

Python: FAST-API

from typing import Optional
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import random

app = FastAPI()

origins = [*]

@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/data")
def read_item( q: Optional[str] = None):

    return { "q": random.uniform(2.5, 10.0) }
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
jax
  • 3,927
  • 7
  • 41
  • 70

1 Answers1

0

Have you enabled and configured cors on your FastAPI config? It would look something like this:

app = FastAPI()
origins = [
  "http://localhost:8080",
]

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