AJAX and Python Error - No 'Access-Control-Allow-Origin' header is present on the requested resource

ajax, javascript, jquery, python

Solution

There is a lot of topics about: Access-Control-Allow-Origin. Read more: http://en.wikipedia.org/wiki/Same_origin_policy

Add this lines after: `self.send_header("Content-type", "application/json")`

self.send_header("Access-Control-Allow-Origin","*");
self.send_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
self.send_header(("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Problem

I'm building a Javascript library that can talk to a simple Python web server using AJAX. Here is the web server class: ``` class WebHandler(http.server.BaseHTTPRequestHandler): def parse_POST(self): ctype, pdict = cgi.parse_header(self.headers['content-type']) if ctype == 'multipart/form-data': postvars = cgi.parse_multipart(self.rfile, pdict) elif ctype == 'application/x-www-form-urlencoded': length = int(self.headers['content-length']) postvars = urllib.parse.parse_qs(self.rfile.read(length), keep_blank_values=1) else: postvars = {} return postvars def do_POST(self): postvars = self.parse_POST() print(postvars) # reply with JSON self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() json_response = json.dumps({'test': 42}) self.wfile.write(bytes(json_response, "utf-8")) ``` And here is the Javascript method I'm using: ``` var send_action = function() { var url = "http://192.168.1.51:8000"; var post_data = {'gorilla': 'man'}; $.post(url, post_data, function(data) { alert("success"); }) .done(function(data) { alert("second success"); }) .fail(function() { alert("error"); }) .always(function() { alert("finished"); }); }; ``` When I run the server and call the JS function the server prints `{'gorilla': 'man'}` but then the browser flashes the error alert followed by the finished alert. In the developer log I have: ``` XMLHttpRequest cannot load http://192.168.1.51:8000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. ``` The same thing happens when I specify *dataType*s in `$.post` like so: ``` $.post(url, post_data, function(data) { alert( "success" ); }, 'json') ``` or ``` $.post(url, post_data, function(data) { alert( "success" ); }, 'jsonp') ``` Both the server and the browser session are on the same machine. Solution Needed to add extra headers after `self.send_header("Content-type", "application/json")`: ``` self.send_header("Access-Control-Allow-Origin", "*"); self.send_header("Access-Control-Expose-Headers", "Access-Control-Allow-Origin"); self.send_header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); ```

Original source