I have a simple tornado server which has the class:
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
print "setting headers!!!"
self.set_header("Access-Control-Allow-Origin", "*")
When a regular (no CORS) request is made, the server answers as expected, including the Access-Control-Allow-Origin header. But when I make a post request coming from different domain (using jQuery.post
), the response is 404 and an error is displayed: "XMLHttpRequest cannot load http://dev-machine:8090/handshake. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8090' is therefore not allowed access. The response had HTTP status code 404."
Can you tell if I miss something? (another header/other configuration/anything else)
Your code is missing preflight, the
OPTIONS
request.https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS:
To implement preflight handler simply add options handler with the same headers and no body.
edit
I've added
x-requested-with
header to allowed list. And here is simple jquery sample:And some really good article about cors - http://dev.housetrip.com/2014/04/17/unleash-your-ajax-requests-with-cors/
The answer by kwarunek led me to the solution for my trouble with the PUT and the DELETE request. The only thing is, that the solution is over-appropriate for the example with GET and POST. In this case the line
is actually sufficient (if the browser doesn't block CORS before all). It is though most relevant for the PUT and DELETE requests. What happens here on the network level can be slightly more complex than in the GET/POST case.
"If the request is a "non-simple" request, the browser first sends a data-less "preflight" OPTIONS request, to verify that the server will accept the request. A request is non-simple when using an HTTP verb other than GET or POST (e.g. PUT, DELETE)." cf. non-simple requests
Now all handlers that inherit from
BaseHandler
are fully CORS-capable:Even with the previous answers I still got the following CORS error:
and the solution is to also allow the headers: