javascript - 如何强制Azure函数将JSON输出到浏览器

标签 javascript json node.js azure azure-functions

我有一个使用此源的 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>

enter image description here 如何强制 azure 始终为我提供 json 输出,而不管请求 header 如何?

最佳答案

您是否尝试过将响应对象的 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 并返回它。

关于javascript - 如何强制Azure函数将JSON输出到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42986354/

相关文章:

javascript - 如何使用 JSON 从 Reddit API 中提取 url 数据

node.js - Node.js 中的密码哈希

javascript - 节点集上的递归回调

javascript - 未定义的 JavaScript 函数错误

javascript - 如何在JavaScript中检查空字符串/未定义字符串/空字符串?

javascript - Node.js - 读取 CSV 文件无法处理行号 > 500 的情况

node.js - 如何使用 .ebextensions 在 Amazon Elastic Beanstalk 中运行 `npm install`

javascript - 如何从文本节点中删除 <br> 并在其包含 <b>、<i>、<a> 等时用 <p> 标记换行

ios - 在 Swift 中使用单例和解析 JSON

java - ArrayList 组项目