python - 无法在 python graphql 框架中启用 CORS/允许 header - ariadne

标签 python reactjs graphql ariadne-graphql

当我从我的 React 前端应用程序连接到我在 python Ariadne 中创建的 graphql 后端时,我收到此错误。

react 查询

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 方法不允许

如何启用 CORS?

最佳答案

Aridne 不支持 CORS。 您需要用 starlette 包装 Ariadne 服务器,而不是允许 CORSMiddleware 中的来源

from starlette.middleware.cors import CORSMiddleware

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

关于python - 无法在 python graphql 框架中启用 CORS/允许 header - ariadne,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62810557/

相关文章:

javascript - 如何在标题组件中使用效果(ReactJS/Next.js)

express - 如何更改 Apollo Express 服务器中的订阅服务器端点?

python - 为什么 Django 应用程序需要 `manage.py` 而不是使用 `__init__py` ?

reactjs - 在 React Router v4 中是否可以订阅路由更改?

python - 如何使用 Python webbrowser 包关闭现有的浏览器选项卡

reactjs - 将本地镜像路径作为两个功能组件之间的 prop 传递

graphql - ApolloBoost 被初始化为不支持的选项 :

javascript - GraphQL 和 Hibernate (ORM)

python - edX 和安装 Django

Python:在递归函数中使用追加 - 覆盖以前的元素