How to return a JSON object from an Azure Function with Node.js

Chris Dellinger picture Chris Dellinger · May 11, 2016 · Viewed 15.6k times · Source

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'
};

Answer

spooky picture spooky · Mar 22, 2017

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'
    }
};

Full Sample below:

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