无法在 python graphql 框架中启用 CORS/允许标头 - ariadne
Posted
技术标签:
【中文标题】无法在 python graphql 框架中启用 CORS/允许标头 - ariadne【英文标题】:Can't enable CORS / allow headers in python graphql framework - ariadne 【发布时间】:2020-10-29 19:04:09 【问题描述】:当我从我的 React 前端应用程序连接到我在 python Ariadne 中创建的 graphql 后端时,我收到了这个错误。
反应查询
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));
阿里阿德涅配置
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)
我在 Chrome 控制台中收到此错误
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
uvicorn 也会打印出来:
INFO: 127.0.0.1:59910 - "OPTIONS / HTTP/1.1" 405 Method Not Allowed
如何启用 CORS?
【问题讨论】:
【参考方案1】:Aridne 不支持 CORS。 您需要用 starlette 包装 Ariadne 服务器,然后允许起源于 CORSMiddleware
from starlette.middleware.cors import CORSMiddleware
(...)
app = CORSMiddleware(GraphQL(schema, debug=True), allow_origins=['*'], allow_methods=("GET", "POST", "OPTIONS"))
【讨论】:
您可能需要添加额外的 headers 参数:allow_headers=['access-control-allow-origin', 'authorization', 'content-type']
以上是关于无法在 python graphql 框架中启用 CORS/允许标头 - ariadne的主要内容,如果未能解决你的问题,请参考以下文章
无服务器框架 + AWS + Lambda + DynamoDB + GraphQL + Apollo Server = 无法使 POST 请求工作
在 spring boot 中使用 graphql-java 我无法在嵌套列表中查询数据
无服务器框架+ AWS + Lambda + DynamoDB + GraphQL + Apollo Server =无法使POST请求工作