Python 3.x SimpleHTTPRequestHandler没有输出任何响应

时间:2013-07-02 20:26:34

标签: ajax windows python-3.x simplehttpserver

我试图在运行于Windows 7 64位的python 3.x中创建一个简单的http服务器。我在Mac上的python 2.7上运行正常,并进行了一些更改以升级到在Windows上运行的python 3.2。

查询时,标题都会正确返回,但浏览器检查器中没有显示任何内容 - 但telnet显示响应已完全收到!

为什么它不会出现在浏览器中?帮助!

代码是:

import sys

import http.server
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler
import usb.core

class MyHandler(SimpleHTTPRequestHandler):

    def __init__(self,req,client_addr,server):
        SimpleHTTPRequestHandler.__init__(self,req,client_addr,server)      

    def do_GET(self):
        r="<h1>Hello World</h1>"
        self.send_response(200)
        self.send_header("Content-type", "application/json;charset=utf-8")

        self.send_header("Content-length", len(r))
        self.end_headers()
        self.wfile.write(r.encode("utf-8"))
        self.wfile.flush()
        print(r)

HandlerClass = MyHandler
Protocol     = "HTTP/1.1"
port = 80

server_address = ('localhost', port)

HandlerClass.protocol_version = Protocol

try:
    httpd = HTTPServer(server_address, MyHandler)
    print ("Server Started")
    httpd.serve_forever()
except KeyboardInterrupt:
    print('Shutting down server')
    httpd.socket.close()

1 个答案:

答案 0 :(得分:1)

我修复了它 - 它需要“Access-Control-Allow-Origin”标题添加:

self.send_header("Access-Control-Allow-Origin","*")

- 做了诀窍!