I am writing a simple python server and using do_GET to return a html by following
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler):
def _writeheaders(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_HEAD(self):
self._writeheaders()
def do_GET(self):
f = open("/full/path/to.html")
self._writeheaders()
self.wfile.write(f.read())
serveraddr = ('localhost', 7070)
srvr = HTTPServer(serveraddr, RequestHandler)
srvr.serve_forever()
in the html a have
<html>
<head>
<title>myChart</title>
<meta charset="UTF-8">
</head>
<div >
...divs...
</div>
<script>
...js functions...
</script>
<body>
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
</body>
</html>
I was able to get the html, however in the browser console says Uncaught SyntaxError: Unexpected token <
at jquery-1.8.2.min.js:1
If I directly open html page in browser, everything is fine so the problem is not in the html
----update----
I was using Chrome and by clicking the error in the console, the source showed up was the html itself instead of the js file. I tried to specify the full path of the js file in the html, however it still showed me the html file in the error
There js file works fine when I open the html file by enter it dir in the browser
Also in the python console I can see:
127.0.0.1 - - [28/Jun/2015 00:12:28] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [28/Jun/2015 00:12:28] "GET /full/path/to/js/jquery-1.8.2.min.js HTTP/1.1" 200 -
127.0.0.1 - - [28/Jun/2015 00:12:28] "GET /favicon.ico HTTP/1.1" 200 -
答案 0 :(得分:0)
您的RequestHandler
将提供您的HTML网页,无论网址是什么 - 该网址是/
,/index.html
,/favicon.ico
还是(在您的情况下){{ 1}}。如果您希望/js/jquery-1.8.2.min.js
再次提供实际的JavaScript文件而非HTML页面,则需要特别处理,例如:
/js/jquery-1.8.2.min.js
您可能希望稍微更改一下,以便请求JavaScript文件提供适当的def do_GET(self):
if self.path == '/js/jquery-1.8.2.min.js':
filename = 'js/jquery-1.8.2.min.js'
else:
filename = 'index.html'
with open(filename, 'r') as f:
self._writeheaders()
self.wfile.write(f.read())
标头而不是Content-Type: text/javascript
,Content-Type: text/html
返回与{HEAD
一致的标头1}}等等。
此外,如果您开始提供大型文件,您可能需要考虑使用shutil.copyfileobj
将文件中的数据复制到GET
,而不是将整个文件读入内存并进行编写全力以赴。