I have the following shell script for a very simple HTTP server:
#!/bin/sh
echo "Serving at http://localhost:3000"
python -m SimpleHTTPServer 3000
I was wondering how I can enable or add a CORS header like Access-Control-Allow-Origin: *
to this server?
ベストアンサー1
Unfortunately, the simple HTTP server is really that simple that it does not allow any customization, especially not for the headers it sends. You can however create a simple HTTP server yourself, using most of SimpleHTTPRequestHandler
, and just add that desired header.
そのためには、ファイルsimple-cors-http-server.py
(または何か)を作成し、使用している Python のバージョンに応じて、次のいずれかのコードをその中に挿入するだけです。
その後、これを実行するpython simple-cors-http-server.py
と、変更されたサーバーが起動し、すべての応答に CORS ヘッダーが設定されます。
とともにシバン上部で、ファイルを実行可能にして PATH に配置すると、それを使用して実行できるようになりますsimple-cors-http-server.py
。
Python 3 ソリューション
Python 3ではSimpleHTTPRequestHandler
そしてHTTPServer
からhttp.server
モジュールサーバーを実行するには:
#!/usr/bin/env python3
from http.server import HTTPServer, SimpleHTTPRequestHandler, test
import sys
class CORSRequestHandler (SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__':
test(CORSRequestHandler, HTTPServer, port=int(sys.argv[1]) if len(sys.argv) > 1 else 8000)
Python 2 ソリューション
Python 2ではSimpleHTTPServer.SimpleHTTPRequestHandler
そしてそのBaseHTTPServer
モジュールサーバーを実行します。
#!/usr/bin/env python2
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
class CORSRequestHandler (SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__':
BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)
Python 2 & 3 ソリューション
Python 3 と Python 2 の両方の互換性が必要な場合は、両方のバージョンで動作するこのポリグロット スクリプトを使用できます。最初に Python 3 の場所からインポートを試み、そうでない場合は Python 2 にフォールバックします。
#!/usr/bin/env python
try:
# Python 3
from http.server import HTTPServer, SimpleHTTPRequestHandler, test as test_orig
import sys
def test (*args):
test_orig(*args, port=int(sys.argv[1]) if len(sys.argv) > 1 else 8000)
except ImportError: # Python 2
from BaseHTTPServer import HTTPServer, test
from SimpleHTTPServer import SimpleHTTPRequestHandler
class CORSRequestHandler (SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__':
test(CORSRequestHandler, HTTPServer)