Sefaria / Sefaria-Project

New Interfaces for Jewish Texts
https://www.sefaria.org
653 stars 265 forks source link

CORS / Access-Control-Allow-Origin #155

Closed dakom closed 6 years ago

dakom commented 9 years ago

Problem

Currently, the api cannot be used within javascript from third-party sites. Consider the following example run from a staging server on http://localhost:8080 (not sefaria.org):

$.ajax({
        url: "http://www.sefaria.org/api/index/titles",
        dataType: 'json'})
        .done(function(retObj) { alert('success!'); console.log(retObj); })
        .fail(function() { alert('fail!'); })
        .always(function() { });

The result is a "fail" alert and this error in the console:

XMLHttpRequest cannot load http://www.sefaria.org/api/index/titles. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Solution

For something like a GET/JSON API - I think setting the Access-Control-Allow-Origin header to "*" should be available and made to be secure.

I'm not familiar with the codebase here, or really python, but just looking at where content-type is set it seems that Access-Control-Allow-Origin: * can be added to wherever the Content-Type is set to "application/json", like maybe:

https://github.com/blockspeiser/Sefaria-Project/blob/master/sefaria/client/util.py#L52 and https://github.com/blockspeiser/Sefaria-Project/blob/master/reader/views.py#L766

?

blockspeiser commented 9 years ago

We're looking into adding CORS support now. We may just be able to do this at the Apache level (researching security implications).

In the meantime, we support cross domain API requests with JSONP. In your example you should just be able to change to the data type to "JSONP" and add "?callback=?" to the requested URL. https://learn.jquery.com/ajax/working-with-jsonp/

Here's another example using some slightly different jQuery syntax: https://github.com/blockspeiser/Sefaria-Project/blob/master/templates/static/random-walk-through-torah.html#L53

dakom commented 9 years ago

Cool, will try the workarounds in the meantime- thanks! :)

blockspeiser commented 6 years ago

CORS is now open on https://www.sefaria.org.