Reputation: 2859
I have the following base class:
class CorsHandler(tornado.web.RequestHandler):
def set_default_headers(self):
super(CorsHandler, self).set_default_headers()
self.set_header('Access-Control-Allow-Origin', self.request.headers.get('Origin', '*'))
self.set_header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS')
self.set_header('Access-Control-Allow-Credentials', 'true')
self.set_header('Access-Control-Allow-Headers', ','.join(
self.request.headers.get('Access-Control-Request-Headers', '').split(',') +
['Content-Type']
))
self.set_header('Content-Type', 'application/json')
def options(self, *args, **kwargs):
pass
And the following handler:
def get(self, resource_id=None, field=None):
try:
if resource_id is None:
response = self.resource.query.filter_by(is_deleted=False).all()
else:
record = self.resource.query.get(int(resource_id))
if field is None:
response = record
else:
response = {field: getattr(record, field)}
self.db.session.commit()
except Exception, e:
self.db.session.rollback()
self.send_error(500, message=e.message)
self.write(response)
Everything's pretty straightforward, except Content-Type is not getting set. Note that any other header is being set properly.
What's going on?
Upvotes: 4
Views: 8959
Reputation: 16770
It seems this is a 304 Not Modified
response. Remember only the first 200 OK
response contains Content-Type
header. The following response will neglect this header if you are requesting the same resource.
And beware that you don't actually need to explicitly set the Content-Type
. If you look into the source code of Tornado, you will find this in the comment of write(self, chunk)
:
If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be
application/json
. (if you want to send JSON as a differentContent-Type
, call set_header after calling write()).
Upvotes: 9