Simple Web Server with CORS
When your browser refuses to load local files
Sometimes we want our browser to be able to load a local file
- .json
- .js
- ... etc
But the resource is blocked. Running a local
The Python Docs Example will get you 80% there. However, you may encounter
You can read the spec on MDN which goes a great amount of detail on the protocol. But for local development, when we just want it to run we can fix these errors by adding one header to our response.
Created: 2019-11-21
Updated: 2021-12-26
import os
import argparse
import socketserver
from functools import partial
from http.server import SimpleHTTPRequestHandler
class CORSRequestHandler(SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# Note that if you're making a request from 127.0.0.1 to localhost - CORS applies!
parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('--directory', '-d', default=os.getcwd(),
help='Specify alternative directory '
'[default:current directory]')
parser.add_argument('port', action='store',
default=8000, type=int,
nargs='?',
help='Specify alternate port [default: 8000]')
args = parser.parse_args()
print(f"Serving root at {args.directory}")
handler_class = partial(CORSRequestHandler, directory=args.directory)
with socketserver.TCPServer((args.bind, args.port), CORSRequestHandler) as httpd:
httpd.serve_forever()
I keep a .bat file handy to quickly launch this for specific projects
CALL C:\path\to_your_venv\activate.bat
ECHO "Starting CORS Server"
cd C:\path\to_module
python server.py -d "C:\path\to_server_root\directory"
PAUSE