如何强制 Azure 函数向浏览器输出 JSON

How can I force Azure function to output JSON to browsers

我使用此源设置了 azure 函数:

module.exports = function(context, req) {
    //this is the entire source, seriously
    context.done(null, {favoriteNumber : 3});
};

当我使用像 postman 这样的工具访问它时,我得到了一个很好的 JSON 输出,就像我想要的那样:

{
  "favoriteNumber": 3
}

问题是当我在浏览器(chrome、firefox 等)中访问它时,我看到:

<ArrayOfKeyValueOfstringanyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"><KeyValueOfstringanyType><Key>favoriteNumber</Key><Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema" i:type="d3p1:int">3</Value></KeyValueOfstringanyType></ArrayOfKeyValueOfstringanyType>

我怎样才能强制 azure 始终给我一个 json 输出,而不管请求 headers?

您是否尝试过将响应 object 的 Content-Type 明确设置为 application\json

module.exports = function(context, req) {
    res = {
        body: { favoriteNumber : 3},
        headers: {
            'Content-Type': 'application/json'
        }
    };

context.done(null, res);
};

默认情况下,功能配置为内容协商。当你调用你的函数时,Chrome 发送一个 header 就像

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

因此,它请求 XML 并返回。