-
-
Notifications
You must be signed in to change notification settings - Fork 388
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to set CORS on per endpoint basis? #114
Comments
Hi @dondyb, Happy holidays! Yes, a middleware will make it be for all requests, here's how you could do it for a single API endpoint:
Or, if you want to make it in a reusable fashion you could do one of the following: A requires function:
Or, if you want to be really fancy, you could use a directive:
Let me know if this answeres your question. Thanks! ~Timothy |
Hi @timothycrosley, Thanks. It does work. Didn't realize if that simple 💃 |
hey,
it adds the header too all request, even 404, 405... |
Hi @timothycrosley, two questions related to this question:
|
@radumas the '*' is a generic solution, if you want to have fine-grained access control this unfortunately will be bound to your application specifics, therefore in any case documenting it's not very helpful, as this is beyond the hug's (or underlying falcon) responsibility. Here a more complete, almost production sample we use, for generic permissive access, two options: 1. Pure hug middleware @hug.response_middleware()
def CORS(request, response, resource):
response.set_header('Access-Control-Allow-Origin', '*')
response.set_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
response.set_header(
'Access-Control-Allow-Headers',
'Authorization,Keep-Alive,User-Agent,'
'If-Modified-Since,Cache-Control,Content-Type'
)
response.set_header(
'Access-Control-Expose-Headers',
'Authorization,Keep-Alive,User-Agent,'
'If-Modified-Since,Cache-Control,Content-Type'
)
if request.method == 'OPTIONS':
response.set_header('Access-Control-Max-Age', 1728000)
response.set_header('Content-Type', 'text/plain charset=UTF-8')
response.set_header('Content-Length', 0)
response.status_code = hug.HTTP_204 2. You don't want to mess hug up with constant middleware, use nginx:
|
@danigosa this is a great answer. Wish this would be documented somewhere so people don't spend days looking for a solution. |
@sameh-sharaf good call! I've added an initial answer to this question on the projects FAQ documentation to start: https://hugapi.github.io/hug/FAQ/ I apologize for the documentation gap! ~Timothy |
Hi,
Any idea on how to enable CORS or set Header on per end point basis ? If I use middleware it will be for all request, won't it ?
Thanks in advance
The text was updated successfully, but these errors were encountered: