pythonreactjsgraphqlariadne-graphql

Can't enable CORS / allow headers in python graphql framework - ariadne


When i connec't from my React frontend app to my graphql backend created in python Ariadne i get this error.

React query

const uri = 'http://localhost:8000/'
const link = new HttpLink({ 
    uri,

const client = new ApolloClient({ 
    link,
    cache: new InMemoryCache(),
});

});

client.query({
  query: gql`
{
    "myquery"
  }
}
  `
}).then(result => console.log(result));

Ariadne config

from ariadne import make_executable_schema, load_schema_from_path
from ariadne.asgi import GraphQL

type_defs = load_schema_from_path(SCHEMA_FILE)

schema = make_executable_schema(type_defs, *types)
app = GraphQL(schema, debug=True)

I get this error in Chrome console

Access to fetch at 'http://localhost:8000/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

POST http://localhost:8000/ net::ERR_FAILED

Also uvicorn prints out:

INFO: 127.0.0.1:59910 - "OPTIONS / HTTP/1.1" 405 Method Not Allowed

How to enable CORS?


Solution

  • Aridne does not support CORS. You need to wrap Ariadne server with starlette, and than allow origins in CORSMiddleware

    from starlette.middleware.cors import CORSMiddleware
    
    (...)
    app = CORSMiddleware(GraphQL(schema, debug=True), allow_origins=['*'], allow_methods=("GET", "POST", "OPTIONS"))