如何响应JSON-RPC s上的HTTP选项请求

2024-05-13 22:19:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我的JSON-RPC客户端(使用dojo JSON-RPC的浏览器)向My server.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服务可以从网络访问。

现在的问题是,浏览器(比如Firefox)希望听者说什么?或者问题出在别处?


Tags: 服务器comjsonhttpaccessapplication浏览器rpc
3条回答

检查我的密码。它适用于运行在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) 

添加代码并尝试,这对我很有用:

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')

请参阅CORS Specification

(顺便说一下,有一个HTTP的头注册表,请参见http://www.iana.org/assignments/message-headers/prov-headers.htmlhttp://www.iana.org/assignments/message-headers/perm-headers.html,这将为您指出正确的规范)。

相关问题 更多 >