단순 HTTP 서버에서 액세스 제어 사용
매우 간단한 HTTP 서버에 대한 다음 셸 스크립트가 있습니다.
#!/bin/sh
echo "Serving at http://localhost:3000"
python -m SimpleHTTPServer 3000
이 서버 와 같은 CORS 헤더를 어떻게 활성화하거나 추가 할 수 있는지 궁금 Access-Control-Allow-Origin: *
합니다.
안타깝게도 간단한 HTTP 서버는 특히 보내는 헤더가 아닌 사용자 정의를 허용하지 않을 정도로 간단합니다. 그러나 대부분의을 사용하여 간단한 HTTP 서버를 직접 만들고 SimpleHTTPRequestHandler
원하는 헤더를 추가 할 수 있습니다.
이를 위해 파일 simple-cors-http-server.py
(또는 기타)을 만들고 사용중인 Python 버전에 따라 다음 코드 중 하나를 내부에 넣으십시오.
그런 다음 할 수 있으며 python simple-cors-http-server.py
모든 응답에 대해 CORS 헤더를 설정하는 수정 된 서버를 시작합니다.
으로 오두막 상단의 파일을 실행하고 사용자의 PATH에 넣어, 당신은 단지 사용하여 실행할 수 있습니다 simple-cors-http-server.py
도.
Python 3 솔루션
파이썬 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에 대한 호환성이 필요한 경우 두 버전 모두에서 작동하는이 polyglot 스크립트를 사용할 수 있습니다. 먼저 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)
http-server와 같은 대안을 시도하십시오.
As SimpleHTTPServer is not really the kind of server you deploy to production, I'm assuming here that you don't care that much about which tool you use as long as it does the job of exposing your files at http://localhost:3000
with CORS headers in a simple command line
# install (it requires nodejs/npm)
npm install http-server -g
#run
http-server -p 3000 --cors
Need HTTPS?
If you need https in local you can also try caddy or certbot
Some related tools you might find useful
ngrok: when running
ngrok http 3000
, it creates an urlhttps://$random.ngrok.com
that permits anyone to access yourhttp://localhost:3000
server. It can expose to the world what runs locally on your computer (including local backends/apis)localtunnel: almost the same as ngrok
now: when running
now
, it uploads your static assets online and deploy them tohttps://$random.now.sh
. They remain online forever unless you decide otherwise. Deployment is fast (except the first one) thanks to diffing. Now is suitable for production frontend/SPA code deployment It can also deploy Docker and NodeJS apps. It is not really free, but they have a free plan.
I had the same problem and came to this solution:
class Handler(SimpleHTTPRequestHandler):
def send_response(self, *args, **kwargs):
SimpleHTTPRequestHandler.send_response(self, *args, **kwargs)
self.send_header('Access-Control-Allow-Origin', '*')
I simply created a new class inheriting from SimpleHTTPRequestHandler that only changes the send_response
method.
You'll need to provide your own instances of do_GET() (and do_HEAD() if choose to support HEAD operations). something like this:
class MyHTTPServer(SimpleHTTPServer):
allowed_hosts = (('127.0.0.1', 80),)
def do_GET(self):
if self.client_address not in allowed_hosts:
self.send_response(401, 'request not allowed')
else:
super(MyHTTPServer, self).do_Get()
참고URL : https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server
'Programing' 카테고리의 다른 글
문자열에 숫자 만 포함되어 있는지 파이썬에서 어떻게 확인합니까? (0) | 2020.08.16 |
---|---|
C #에 단 수화-단어를 복수화하는 알고리즘이 있습니까? (0) | 2020.08.16 |
GoogleTest : 테스트를 건너 뛰는 방법? (0) | 2020.08.16 |
Rails 애플리케이션의 쿠키 오버플로? (0) | 2020.08.16 |
Blob을 base64로 변환 (0) | 2020.08.16 |