Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
python3 -m http.server PORT for a CORS world
#!/usr/bin/env python3
# It's python3 -m http.server PORT for a CORS world
from http.server import HTTPServer, SimpleHTTPRequestHandler
import sys
class CORSRequestHandler(SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', '*')
self.send_header('Access-Control-Allow-Headers', '*')
self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
return super(CORSRequestHandler, self).end_headers()
def do_OPTIONS(self):
host = sys.argv[1] if len(sys.argv) > 2 else ''
port = int(sys.argv[len(sys.argv)-1]) if len(sys.argv) > 1 else 8080
print("Listening on {}:{}".format(host, port))
httpd = HTTPServer((host, port), CORSRequestHandler)
Copy link

djeikyb commented Aug 13, 2020

If you're making requests with credentials turned on, you'll need to include:

self.send_header('Access-Control-Allow-Credentials', 'true')

Which causes a new problem! When credentials are enabled, the allow-headers directive * doesn't function as a wildcard, instead as a literal value. I used this as a quick little video server, and need to use the range header:

self.send_header('Access-Control-Allow-Headers', 'range')

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