Skip to content

Instantly share code, notes, and snippets.

Embed
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):
self.send_response(200)
self.end_headers()
host = sys.argv[1] if len(sys.argv) > 2 else '0.0.0.0'
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)
httpd.serve_forever()
@djeikyb

This comment has been minimized.

Copy link

@djeikyb 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
You can’t perform that action at this time.