Strange JQuery Error “code 501, message Unsupported method OPTIONS”

前端 未结 4 1140
Happy的楠姐
Happy的楠姐 2020-12-10 14:29

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

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

It\'s fine to t

相关标签:
4条回答
  • 2020-12-10 14:33

    Looks like a CORS preflight request (https://developer.mozilla.org/En/HTTP_access_control)

    I guess you are trying to access to a different domain/port. Depending on the request, the browser will send a preflight request (an OPTION request) to know if the server accepts the set of Headers or HTTP method you wanted to send in the first place. If the server responds OK, the browser will send the real request.

    Looks like that Python server doesn't implement OPTIONs requests, hence the error.

    Tip: Network inspection tools (tcpdump, wireshark, ngrep...) help a lot when dealing with http requests and/or network errors.

    0 讨论(0)
  • 2020-12-10 14:39

    You may also need to add fields such as "Content-Type" to the allowed headers.

    self.send_header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type") 
    
    0 讨论(0)
  • 2020-12-10 14:46

    It look like a Cross-Origin Resource Sharing (CORS) preflight request.

    Since CORS is a specification that is strongly related to a server configuration, I recommend to read http://enable-cors.org/

    There you'll see more about implementing CORS for your specific platform.

    0 讨论(0)
  • 2020-12-10 14:56

    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) 
    
    0 讨论(0)
提交回复
热议问题