Skip to content
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

Automatic handling of OPTIONS during POST #1484

Closed
AdrianTeng opened this issue Dec 10, 2014 · 3 comments
Closed

Automatic handling of OPTIONS during POST #1484

AdrianTeng opened this issue Dec 10, 2014 · 3 comments

Comments

@AdrianTeng
Copy link
Contributor

Say I have a route that expects some json POST body:

@view_config(route_name='foo', renderer='json')
def foo(request):
    return fancy_transform(request.json_body)

It works all and well in a standard scenario, as shown in the documentation here. But if you are doing a Cross-Origin Resource Sharing, then the standard is to first run a OPTIONS request to get server's approval, then execute the POST request.

In my particular case, I'm using AngularJS's $http to run POST with some json body onto the route foo. AngularJS then first run a OPTIONS, which has no body, and the route return a 500, since request.json_body fails to decode empty body.

There are currently few workaround:

  • Make function foo only handles request_method='POST', add another function that has same route_name and handle request_method='OPTIONS'. The extra function can return an empty dict. Alternatively just extend function foo to handle cases with different request_method
  • On AngularJS, use customised header {'Content-Type': 'application/x-www-form-urlencoded'}. This will make $http skipping OPTIONS and go straight into POST

I feel the handling of OPTIONS request should be done by Pyramid automatically.

@tseaver
Copy link
Member

tseaver commented Dec 10, 2014

The OPTIONS method is sent as part of a CORS preflighted request. Pyramid cannot handle it automatically, because it involves application policy (what headers to set on the response). This issue needs to be addressed by a custom decorator (defined in your app) or a higher-level framework (e.g., Cornice or rest-toolkit).

@tseaver tseaver closed this as completed Dec 10, 2014
@digitalresistor
Copy link
Member

@AdrianTeng Your first "workaround" is actually the only and correct answer for Pyramid.

@AdrianTeng
Copy link
Contributor Author

@tseaver Fair enough, but I think this is worth documenting. I'll add some examples to here later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants