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

北战南征 提交于 2019-11-28 11:12:36
Xiao

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

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

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.

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.

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