django rest api usage and CORS problem

68 views
Skip to first unread message

Oğuz Yarımtepe

unread,
Nov 2, 2016, 9:27:18 AM11/2/16
to Falcon Framework
I have a django app and at the template part i have javascript function calling the rest api:


<!-- Custom Theme JavaScript -->
<script src="/static/js/select-autofiller.js"></script>


At the js file i am filling a select box according to the returned json response

$('#field1').change(function(){

var var1=$("#filed2").val();
var var2=$("#field1 option:selected").text();


url="http://www.foo.com:8080/" + var1 + "/" + var2 + "/";


$.get(url, function( data ) {
alert( "Load was performed." + data);
});



});

The Django web app is running on www.foo.com:8000

At the rest api side, falcon is running and i installed falcon-cors

import falcon

from wsgiref import simple_server

from falcon_cors import CORS


check_python()

cors = CORS(allow_origins_list=settings.ALLOWED_ORIGINS)

api = falcon.API(
media_type='application/json',
middleware=[
# json.RequireJSON(),
# json.JSONTranslator(),
https.RequireHTTPS(),
headers.BaseHeaders(),
handle_404.WrongURL(),
cors.middleware
],
)

***
route definitions
****

httpd = simple_server.make_server('0.0.0.0', 8080, api)
httpd.serve_forever()

ALLOWED_ORIGINS is a list: ['www.foo.com:8000', 'www.foo.com:8080']

Still when i select the box and triggered the js at the Django web app, i am getting 

XMLHttpRequest cannot load http://www.foo.com:8080/var1/var2. Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.foo.com:8000' is therefore not allowed access. The response had HTTP status code 400.

I couldn't find ow to fix it. 
Any idea?

Colton Leekley-Winslow

unread,
Nov 4, 2016, 1:00:59 PM11/4/16
to Falcon Framework
An origin is comprised of (uri-scheme, uri-host, uri-port).  The error you posted said the origin "http://www.foo.com:8000" was disallowed, which includes "http://" as the uri-scheme component.  Your allow_origins list however does not include uri-scheme in the allowed origins.  This is probably the fault of my README example not including scheme, I will make sure to update that!  In situations like this you can also pass the logger attribute to your CORS object, and if you enable it for log level debug you will see messages when CORS requests get denied.  

TL;DR  Try adding "http://" to the values in your allow_origins list, and/or enabling debug logging.
Reply all
Reply to author
Forward
0 new messages