json - 如何使用 Node.js 从 Azure 函数返回 JSON 对象

标签 json node.js azure azure-functions

使用 Azure Functions,您需要做什么才能从用 node.js 编写的函数返回正文中的 JSON 对象?我可以轻松返回一个字符串,但是当我尝试返回如下所示的 json 对象时,我似乎没有返回任何内容。

context.res = {
   body: jsonData,
   contentType: 'application/json'
};

最佳答案

基于我最近的测试(2017 年 3 月)。您必须显式地将内容类型添加到响应 header 才能获取 json,否则数据会在浏览器中显示为 XML。

"Content-Type":"application/json"

res = {
    status: 200, /* Defaults to 200 */
    body: {message: "Hello " + (req.query.name || req.body.name)},
    headers: {
        'Content-Type': 'application/json'
    }
};

完整示例如下:

module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    context.log(context);

    if (req.query.name || (req.body && req.body.name)) {
        res = {
            // status: 200, /* Defaults to 200 */
            body: {message: "Hello " + (req.query.name || req.body.name)},
            headers: {
                'Content-Type': 'application/json'
            }
        };
    }
    else {
        res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
    context.done(null, res);
};

关于json - 如何使用 Node.js 从 Azure 函数返回 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37152658/

相关文章:

javascript - Loopback:我们如何修改内置模型函数的返回数据

javascript - Node.js:异步回调困惑

azure - 如何使用 Azure DevOps 监控测试进度?

azure - 在 VS 2017 中设置新项目时找不到 Azure Functions

jQuery 找不到动态添加的 DOM 对象?

json - 在 golang 中对没有结构的 JSON 数据进行最小程度的修改

javascript - mongoose、express 和 node.js 中回调函数的参数

java - 我可以在 Spring Boot 中为函数添加 "get"前缀吗

javascript - 使用 $http 服务将数据发布到本地 json 文件时未找到元素错误

caching - azure共享缓存和新的azure redis缓存有什么区别?