如何使用 Node.js 从 Azure 函数返回 JSON 对象 [英] How to return a JSON object from an Azure Function with Node.js

查看:16
本文介绍了如何使用 Node.js 从 Azure 函数返回 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

With Azure Functions, what do you need to do to return a JSON object in the body from a function written in node.js? I can easily return a string, but when I try to return a json object as shown below I appear to have nothing returned.

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

推荐答案

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

Based on my recent testing (March 2017). You have to explicitly add content type to response headers to get json back otherwise data shows-up as XML in browser.

"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);
};

这篇关于如何使用 Node.js 从 Azure 函数返回 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆