问题描述
我有这个mootools请求:
I have this mootools request:
new Request({
url: 'http://localhost:8080/list',
method: 'get',
}).send();
和一个处理它的小型python服务器:
and a small python server that handles it with this:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import subprocess
class HttpHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/list':
self.list()
else:
self._404()
def list(self):
self.response200()
res = "some string"
self.wfile.write(res)
def _404(self):
self.response404()
self.wfile.write("404\n")
def response200(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Headers', 'X-Request, X-Requested-With')
self.send_header('Content-type', 'application/json')
self.end_headers()
def response404(self):
self.send_response(404)
self.send_header('Content-type', 'application/json')
self.end_headers()
def main():
try:
server = HTTPServer(('', 8080), HttpHandler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
if __name__ == '__main__':
main()
我尝试发出此请求时,会收到以下错误:
When I attempt to make this request, I get these errors:
OPTIONS http://localhost:8080/ 501 (Unsupported method ('OPTIONS'))
XMLHttpRequest cannot load http://localhost:8080/. Origin null is not allowed by Access-Control-Allow-Origin.
我不知道发生了什么。有人可以帮助我吗
I'm not sure what's going on. Can someone help me out??
推荐答案
与响应字符串告诉你: / localhost:8080/501(不支持的方法('OPTIONS'))
exactly as the response string tells you: OPTIONS http://localhost:8080/ 501 (Unsupported method ('OPTIONS'))
当javascript尝试从其他来源请求资源时,首先询问其他服务器,目标,如果确定从另一个来源发出请求,这正是 Access-Control *
标头做的。但此请求不会在正常的 GET
中发生,因为这将实际执行请求,而是使用 OPTIONS
方法,该方法的唯一原因是告知客户他们允许做什么,而实际上不做。
When javascript attempts to request a resource from another origin, modern browsers first ask the other server, the target, if it is ok to make that request from another origin, that's exactly what the Access-Control*
headers do. but this request does not happen in a normal GET
, since that would be actually performing the request anyway, and instead use the OPTIONS
method, which exists for the sole reason to inform clients what they are allowed to do, without actually doing it.
因此,您需要一个 do_OPTIONS
方法,它可能类似:
So, you need a do_OPTIONS
method, which might look something like:
def do_OPTIONS(self):
if self.path in ('*', '/list'):
self.send_response(200)
self.send_header('Allow', 'GET, OPTIONS')
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Headers', 'X-Request, X-Requested-With')
else:
self.send_response(404)
self.send_header('Content-Length', '0')
self.end_headers()
这篇关于Mootools请求获取“501不支持的方法('OPTIONS')”响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!