我有这个 mootools 请求:
new Request({
url: 'http://localhost:8080/list',
method: 'get',
}).send();
和一个小型 python 服务器,用这个来处理它:
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()
当我尝试发出此请求时,出现以下错误:
OPTIONS http://localhost:8080/ 501 (Unsupported method ('OPTIONS'))
XMLHttpRequest cannot load http://localhost:8080/. Origin null is not allowed by Access-Control-Allow-Origin.
我不确定发生了什么事。有人可以帮我吗?
最佳答案
正如响应字符串告诉您的那样:OPTIONS http://localhost:8080/501(不支持的方法('OPTIONS'))
当 javascript 尝试从另一个源请求资源时,现代浏览器首先询问其他服务器(目标)是否可以从另一个源发出该请求,这正是 Access-Control*
标题即可。但此请求不会发生在普通的 GET
中,因为无论如何都会实际执行该请求,而是使用 OPTIONS
方法,该方法存在的唯一原因是告知客户他们可以做什么,但实际上并没有这样做。
因此,您需要一个 do_OPTIONS
方法,它可能类似于:
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()
关于python - Mootools 请求获得 "501 Unsupported method (' OPTIONS')"响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10157581/