Skip to content

Instantly share code, notes, and snippets.

@pirafrank
Created May 21, 2020 08:44
Show Gist options
  • Save pirafrank/4089fd5532b4fdafac2bc3d476dd096e to your computer and use it in GitHub Desktop.
Save pirafrank/4089fd5532b4fdafac2bc3d476dd096e to your computer and use it in GitHub Desktop.
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
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