用jQuery和Ajax将请求发送到API,为什么总得405响应?

我在Tornado中遇到了问题。我有一个API端点,用于在Tornado中使用PUT HTTP方法。我还有一个Web应用程序,它用jQuery和Ajax将请求发送到这个API,但是我总是得到405响应,因为请求是以HTTP方法选项的形式进行的。我理解它的工作方式,并配置了“Tornado服务器”来支持它。但即使如此我还是没能解决问题。有人能帮我吗?

这是我的服务器代码:

class BaseHandler(RequestHandler):
   def __init__(self, *args, **kwargs):
        super(BaseHandler, self).__init__(*args, **kwargs)
        self.set_header('Cache-Control', 'no-store, no-cache, must-   revalidate, max-age=0')
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "Content-Type")
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS')

多谢!

if you don't define put method return 405

class Handler(tornado.web.RequestHandler):
    def put(self):
        self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "Content-Type")
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS')

[I 170205 04:56:35 web:1971] 200 PUT

You need to add an options handler that just sends the headers with no body:

def options(self):
    # no body
    self.set_status(204)
    self.finish()

See Tornado server: enable CORS requests for a complete code snippet.

Or else just install the tornado-cors package:

pip install tornado-cors

That will add the necessary handlers for you, and ensure the right response headers get sent.