-
-
Save gpaciga/2099b13ea21dcdd5a849b5e41ef2c17d to your computer and use it in GitHub Desktop.
Python 3: serve the current directory as HTTP while setting CORS headers for XHR debugging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# encoding: utf-8 | |
"""Use instead of `python3 -m http.server` when you need CORS""" | |
import sys | |
from http.server import HTTPServer, SimpleHTTPRequestHandler | |
class CORSRequestHandler(SimpleHTTPRequestHandler): | |
def end_headers(self): | |
self.send_header('Access-Control-Allow-Origin', '*') | |
self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS') | |
self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate') | |
return super(CORSRequestHandler, self).end_headers() | |
def do_OPTIONS(self): | |
self.send_header('Access-Control-Allow-Origin', '*') | |
self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS') | |
self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate') | |
return super(CORSRequestHandler, self).end_headers() | |
port = int(sys.argv[1]) if len(sys.argv) > 0 and sys.argv[1] else 8080 | |
print(f'starting server on port {port}') | |
httpd = HTTPServer(('localhost', port), CORSRequestHandler) | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment