Instantly share code, notes, and snippets.

Embed
What would you like to do?
Allow CORS with python simple http server
import SimpleHTTPServer
class CORSHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all circumstances), or
None, in which case the caller has nothing further to do.
"""
path = self.translate_path(self.path)
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
for index in "index.html", "index.htm":
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
# Always read in binary mode. Opening files in text mode may cause
# newline translations, making the actual size of the content
# transmitted *less* than the content-length!
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Content-Length", str(fs[6]))
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
return f
if __name__ == "__main__":
import os
import SocketServer
PORT = 31338
Handler = CORSHTTPRequestHandler
#Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
@ReneCode

This comment has been minimized.

ReneCode commented Mar 1, 2015

It works - Thank you.

@desaroxx

This comment has been minimized.

desaroxx commented Jul 21, 2015

thank you!

@moo3

This comment has been minimized.

moo3 commented Oct 12, 2015

Works perfectly. I've updated line 53 to have the port number passed in dynamically.

#from
PORT = 31338

#to
import sys
PORT = sys.argv[1]

#usage
python server.py 8080
@fasiha

This comment has been minimized.

fasiha commented Nov 29, 2015

@moo3 for custom port, you probably need:

    PORT = (len(sys.argv) > 1 and int(sys.argv[1])) or 31338

You need an int, and a default in case the user doesn't want to provide one. Thanks @enjalot, you are a gentleman and a scholar!

@dschere

This comment has been minimized.

dschere commented Sep 2, 2016

No, cors is not working

XMLHttpRequest cannot load http://172.28.2.146:7474/db/data/transaction/commit. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://172.28.2.146:31338' is therefore not allowed access. The response had HTTP status code 401.

@foice

This comment has been minimized.

foice commented Sep 12, 2016

utils.js:25 XMLHttpRequest cannot load http://www.york.ac.uk/teaching/cws/wws/webpage1.html. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:31338' is therefore not allowed access.

@bartathalon

This comment has been minimized.

bartathalon commented Sep 13, 2016

This is not working for me .. still receiving error "has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-origin' header is present on the requested resource."

@mgillam

This comment has been minimized.

mgillam commented Nov 15, 2016

Worked like a charm for me, no issues at all. Thanks for posting it.

@sfpprxy

This comment has been minimized.

sfpprxy commented Nov 28, 2016

Work like a charm, thank you enjalot.

@SaschaFromF

This comment has been minimized.

SaschaFromF commented Feb 2, 2017

works, thanks enjalot

@velulev

This comment has been minimized.

velulev commented May 25, 2017

Thanks for your efforts to help other Enjalot. For some of you who say that it does not work, please check that you have all the necessary headers and they are set correctly. I had to replace the following line

    self.send_header("Content-type", ctype)

with

    if '.json' in self.path:
        self.send_header("Content-type", "application/json")
    else:
        self.send_header("Content-type", ctype)

as I was using this program to send JSON data, but the output was coming as octet-stream, instead of "application/json", so, I managed to make it work by making the above change. Hope it helps someone else.

@shaliniidea

This comment has been minimized.

shaliniidea commented Aug 23, 2017

I am running a Python3-Django application on Linux webserver http://192.168.0.200:8000/, and want to get a resource from a windows webserver http://192.168.0.210/xyz. But I get the following Error

XMLHttpRequest cannot load http://192.168.0.210/xyz/File/music.wav. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.0.200:8000' is therefore not allowed access

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment