Skip to content

Commit c316ce1

Browse files
committed
Add GraphQLView option to disable CORS headers
Use Sanic-CORS extension instead which is mature and flexible
1 parent 560f1cd commit c316ce1

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ def init_graphql(app, loop):
4747
- `jinja_env`: Sets jinja environment to be used to process GraphiQL template. If Jinja’s async mode is enabled (by `enable_async=True`), uses
4848
`Template.render_async` instead of `Template.render`. If environment is not set, fallbacks to simple regex-based renderer.
4949
- `batch`: Set the GraphQL view as batch (for using in [Apollo-Client] or [ReactRelayNetworkLayer])
50+
- `cors`: If `True`, set basic CORS headers in response to CORS preflight requests, otherwise - don't set any CORS headers (It's recommended to use [Sanic-CORS] extension).
5051

5152
You can also subclass `GraphQLView` and overwrite `get_root_value(self, request)` to have a dynamic root value per request.
5253

@@ -73,4 +74,5 @@ This project is licensed under MIT License.
7374
[ReactRelayNetworkLayer]: https://github.com/nodkz/react-relay-network-layer
7475
[Sergey Porivaev]: https://github.com/grazor
7576
[sanic-graphql]: https://github.com/grazor/sanic-graphql
77+
[sanic-cors]: https://github.com/ashleysommer/sanic-cors
7678

sanic_graphql/graphqlview.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ class GraphQLView(HTTPMethodView):
2727
middleware = None
2828
batch = False
2929
jinja_env = None
30+
cors = False
3031
max_age = 86400
3132

3233
_enable_async = True
@@ -168,15 +169,22 @@ def process_preflight(self, request):
168169
https://www.w3.org/TR/cors/#resource-preflight-requests """
169170
origin = request.headers.get('Origin', '')
170171
method = request.headers.get('Access-Control-Request-Method', '').upper()
172+
headers = request.headers.get('Access-Control-Request-Headers', '')
171173

172174
if method and method in self.methods:
173-
return HTTPResponse(
174-
status=200,
175+
if self.cors:
175176
headers={
176177
'Access-Control-Allow-Origin': origin,
177178
'Access-Control-Allow-Methods': ', '.join(self.methods),
178-
'Access-Control-Max-Age': str(self.max_age),
179+
'Access-Control-Allow-Headers': headers,
180+
'Access-Control-Allow-Age': str(self.max_age),
179181
}
182+
else:
183+
headers = {}
184+
185+
return HTTPResponse(
186+
status=200,
187+
headers=headers,
180188
)
181189
else:
182190
return HTTPResponse(

0 commit comments

Comments
 (0)