Content-Type header 没有在龙卷风中设置

Content-Type header not getting set in Tornado

我有以下基础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

以及以下处理程序:

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)

一切都很简单,除了 Content-Type 没有设置。请注意,任何其他 header 都已正确设置。

怎么回事?

这似乎是 304 Not Modified 的回应。请记住,只有第一个 200 OK 响应包含 Content-Type header。如果您请求相同的资源,以下响应将忽略此 header。

请注意,您实际上不需要显式设置 Content-Type。如果你查看 Tornado 的源代码,你会在 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 different Content-Type, call set_header after calling write()).