CORS with python baseHTTPserver 501 (Unsupported method ('OPTIONS')) in chrome

前端 未结 3 527
有刺的猬
有刺的猬 2020-12-17 01:57

Hi I need some help with base authentification while a ajax get/post request to a python baseHTTPserver.

I was able to change some lines of code in the python scrip

3条回答
  •  余生分开走
    2020-12-17 02:11

    The client should issue two requests, first one OPTIONS and then the GET request. The solution presented is not optimal, since we are answering the OPTIONS request with contents.

    def do_OPTIONS(self):
                self.sendResponse(200)
                self.processRequest() # not good!
    

    We should answer the OPTIONS request properly. If we do so, the client will issue the GET request after receiving a proper answer.

    I was getting the 501 Unsupported method ('OPTIONS')) caused by CORS and by requesting the "Content-Type: application/json; charset=utf-8".

    To solve the error, I enabled CORS in do_OPTIONS and enabled clients to request a specific content type.

    My solution:

    def do_OPTIONS(self):
        self.send_response(200, "ok")
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS')
        self.send_header("Access-Control-Allow-Headers", "X-Requested-With")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.end_headers()
    
     def do_GET(self):
        self.processRequest()
    

提交回复
热议问题