Python SimpleHTTPServer Recipe: Enable CORS

Create a file, let's call it, with the code below:

#! /usr/bin/env python

from SimpleHTTPServer import SimpleHTTPRequestHandler, test

class CORSHTTPRequestHandler(SimpleHTTPRequestHandler):

    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        super(CORSHTTPRequestHandler, self).end_headers(self)

if __name__ == '__main__':

Now we can start a server at at port 8000 like so:

$ python
Serving HTTP on port 8000 ...

As with python -m SimpleHTTPServer, we can specify a port as well:

$ python 5000
Serving HTTP on port 5000 ...

This server behaves exactly the same as SimpleHTTPServer, except we send the extra header

Access-Control-Allow-Origin: *

to allow any origin to access the resource.

Further Resources


Comments powered by Disqus