怎样让IE浏览器显示application/json数据而不是下载

在开发API接口时候,当API返回的header中Content-Type: application/json时候,IE默认会保存JSON数据,导致开发者不能及时看到response.
在这里插入图片描述
Firefox,chrome可以正常显示JSON数据

原因

微软IE社区解释这是正常的IE行为,如果需要展示JSON数据,需要将数据放在HTML <pre>或<code>中。

解决方法

1 更改注册表

如果是个人开发使用,有修改注册表权限,可以参照更改注册表方案,修改IE默认的行为。

2 返回text/html

若是多个用户都有看API需求,则需更改API返回类型为text/html,IE才能正常展示。
项目开发使用的是Flask-restplus,Flask-restplus是为API开发设计的,默认返回header中content-type是application/json. 为了能够修改header,使用flask make_response方法返回html页面。(限于此接口仅用浏览器直接查看,如果是数据交互类接口,仍需使用application/json)

@ns.route('/')
class DocumentGetter(Resource):
    def get(self):
        resp = {"your_dict":"content"}
        resp_json = json.dumps(resp, indent=2)
        # use html otherwise IE will download json data not showing
        return make_response(render_template('document.html', details=resp_json), 200)

HTML document.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="detail_doc">{{details}}</pre>
</body>
</html>

reference: access list in JS


版权声明:本文为xdshust原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。