'Python - Access Control Allow Origin
I am new to python and I am trying to fetch data from a python script using http request through jquery ajax call. However, I am getting the below error as the python script does not allow cross domain request.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://somehost.com:8000/gen.py. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
I am not sure what do I need to change in the below script to server cross domain request. To be clear, I am using python v2.6.6 which is installed on Red Hat Enterprise Linux Server release 6.5 (Santiago). Below is the python server code that I have tried so far.
#!/usr/bin/env python
import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable() ## This line enables CGI error reporting
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
handler.cgi_directories = ["/"]
httpd = server(server_address, handler)
httpd.serve_forever()
Here is the jquery code from a html file which is located on different server:
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: "http://somehost.com:8000/gen.py",
type: 'GET',
success: function(data) {
console.log(data);
},
error: function(e) {
console.log(e.message);
}
});
});
});
Any pointer to this is appreciable. Let me know if I should provide any more details.
Thank you in advance.
Solution 1:[1]
As e4c5 mentioned, you need to make a CORS request. Since the jquery isn't being served from the same server that is providing gen.py, you need a header on the python server side to allow the browser to retrieve the resource. This same-origin policy is to prevent cross-site scripting.
To do so with BaseHTTPServer, you're going to need to redefine the request handler and provide a call to self.send_header("Access-Control-Allow-Origin", "*"). This answer shows how to do it with BaseHTTPServer, but it's fairly long and involved.
This answer has a pretty simple implementation of how to set the CORS header on SimpleHTTPServer, which has a similar structure to BaseHTTPServer which you can pretty easily port over.
*Regarding the * in the send_header call, this allows requests from any origin to get gen.py. Depending on what this is, it may not matter but you may want to set a more restrictive policy if it does.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
