奇怪的JQuery错误“代码501,消息不支持的方法选项” [英] Strange JQuery Error "code 501, message Unsupported method OPTIONS"
问题描述
我正在学习JQuery Get方法。我启动了一个Python HTTP服务器:
I am learning the JQuery Get method. I start up a Python HTTP server:
(只需输入命令 Python -m SimpleHTTPServer )。
只需在我的网络浏览器上访问http:// localhost:80即可测试此网络服务器。但是,当我写这个非常简单的JavaScript来访问我的网络服务器。我收到一条错误消息:
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:
代码501,消息不支持的方法('OPTIONS')
我使用jquery.xdomainajax.js库来假设跨域请求JQuery。
I use jquery.xdomainajax.js library which suppose cross domain request JQuery.
这是我的javascript代码:
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>
实际上,如果我将您更改为任何其他网址,例如http://www.google .CA。它运作得很好。但我不知道为什么它不适用于基本的Python HTTP服务器。任何人都可以帮助我吗?
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?
推荐答案
我所做的是编写一个自定义的 HTTPRequestHandler 。我在MyHandler中添加了一个 do-OPTIONS 方法来告诉浏览器我的服务器支持CORS。这是通过发送标题 Access-Control-Allow-Origin,Access-Control-Allow-Methods和Access-Control-Allow-Headers 来完成的。另外,我在 do_GET 方法中添加了self.send_header('Access-Control-Allow-Origin','*')语句。
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")
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)
这篇关于奇怪的JQuery错误“代码501,消息不支持的方法选项”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!