Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

javascript - Strange JQuery Error "code 501, message Unsupported method OPTIONS"

I am learning the JQuery Get method. I start up a Python HTTP server:

(just typing command "Python -m SimpleHTTPServer").

It's fine to test this webserver by just visiting "http://localhost:80" on my web browser. However, when I write this very simple javascript to visit my webserver. I get an error message:

"code 501, message Unsupported method ('OPTIONS')"

I use jquery.xdomainajax.js library which suppose cross domain request JQuery.

Here is my javascript code:

<html>
<head>
<script src="jquery.min.js"></script>
<script src="jquery.xdomainajax.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  u = 'http://localhost:80';
 jQuery.get(u, function(res){       
    $("#data").html(res.responseText)
});
});


</script>
</head>
<body>
<p id="data"></p>
</body>
</html>

Actually, if I change u to any other url, such as "http://www.google.ca". It works quite well. But I have no idea why it does not work for the basic Python HTTP server. Can anyone help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What I do is to write a customized HTTPRequestHandler. I add a do-OPTIONS method inside MyHandler to tell browser my server support CORS. This is done by sending headers Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers. Also, I add a "self.send_header('Access-Control-Allow-Origin', '*')" statement in do_GET method.

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")        
        self.end_headers()
    
    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) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...