开发者

How to respond to HTTP OPTIONS request on a JSON-RPC server

My JSON-RPC client (browser using dojo JSON-RPC) makes a JSON-RPC request (dojo.callRemote) to my JSON-RPC server on myserver.com/12345 (Python 2.5, SimpleJSONRPCServer).

The server then gets a HTTP request with header "OPTIONS / HTTP/1.1", which it can't handle by default, so I wrote a custom handler for this request.

The request head开发者_如何学运维er from the browser says:

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

And the response I'm sending looks like this:

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

But in the browser I get the following error:

Error: Unable to load http://myserver.com:12345 status:0

I verified that the JSON-Service is reachable from the net.

Now the question is, what does the browser (say, Firefox) expect the response hearders to say? Or maybe the problem lies elsewhere?


add code and try, it work fine for me:

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


See the CORS Specification.

(BTW; there's a header registry for HTTP, see http://www.iana.org/assignments/message-headers/prov-headers.html and http://www.iana.org/assignments/message-headers/perm-headers.html, which would have pointed you to the right spec).


Check my code. It works for client javascript code running in Chrome browser.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜