Mootools Request getting “501 Unsupported method ('OPTIONS')” response

余生长醉 提交于 2019-12-10 10:35:57

问题


I have this mootools request:

new Request({
    url: 'http://localhost:8080/list',
    method: 'get',
}).send();

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??


回答1:


exactly as the response string tells you: OPTIONS http://localhost:8080/ 501 (Unsupported method ('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.

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


来源:https://stackoverflow.com/questions/10157581/mootools-request-getting-501-unsupported-method-options-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!