我的JSON-RPC客户端(使用dojo JSON-RPC的浏览器)在 myserver.com/12345 上向我的JSON-RPC服务器发出JSON-RPC请求(dojo.callRemote)(Python 2.5, SimpleJSONRPCServer)。
服务器然后获取带有标题“OPTIONS / HTTP / 1.1”的HTTP请求,默认情况下它无法处理,因此我为此请求编写了一个自定义处理程序。
来自浏览器的请求标头显示:
OPTIONS / HTTP/1.1
Host: myserver:12345
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.8) Gecko/20100214 Linux Mint/8 (Helena) Firefox/3.5.8 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.7,de;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Origin: http://myserver.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: x-requested-with
我发送的回复看起来像这样:
HTTP/1.0 200 OK
Server: BaseHTTP/0.3 Python/2.5
Date: Mon, 05 Apr 2010 18:58:34 GMT
Access-Control-Allow-Method: POST
Access-Control-Allow-Headers: POST
Allow: POST
Content-Type: application/json-rpc
Content-length: 0
但是在浏览器中我收到以下错误:
错误:无法加载http://myserver.com:12345状态:0
我验证了JSON-Service可以通过网络访问。
现在的问题是,浏览器(比方说,Firefox)期望响应听众说什么?或者问题可能在其他地方?
答案 0 :(得分:2)
(顺便说一句;有HTTP的标头注册表,请参阅http://www.iana.org/assignments/message-headers/prov-headers.html和http://www.iana.org/assignments/message-headers/perm-headers.html,这会指向正确的规范。)
答案 1 :(得分:2)
添加代码并尝试,它对我来说很好用:
class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
...
...
def do_OPTIONS(self):
self.send_response(200, "ok")
self.send_header('Access-Control-Allow-Origin', self.headers.dict['origin'])
self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
答案 2 :(得分:0)
检查我的代码。它适用于在Chrome浏览器中运行的客户端JavaScript代码。
class MyHandler(BaseHTTPRequestHandler):
def do_OPTIONS(self):
self.send_response(200, "ok")
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header("Access-Control-Allow-Headers", "X-Requested-With")
def do_GET(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write("<html><body>Hello world!</body></html>")
self.connection.shutdown(1)