Python SimpleHTTPServer Recipe: Enable CORS

Create a file, let's call it cors_http_server.py, 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__':
    test(HandlerClass=CORSHTTPRequestHandler)

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

$ python cors_http_server.py
Serving HTTP on 0.0.0.0 port 8000 ...

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

$ python cors_http_server.py 5000
Serving HTTP on 0.0.0.0 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

Comments powered by Disqus