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

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


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


If your data is a JS object, then this should just work, e.g.

module.exports = function(context, req) {    context.res = {        body: { name: "Azure Functions" }    };    context.done();};

This will return an application/json response.

If instead you have your data in a json string, you can have:

module.exports = function(context, req) {    context.res = {        body: '{ "name": "Azure Functions" }'    };    context.done();};

Which will return an application/json response because it sniffs that it is valid json.


I would like to add one more point. Apart from making the body: a JSON object, the request should also contain proper headers telling server what content type we are interested in. I could see that same Azure function when just invoked via browser using URL gives XML response, but when invoking from script or tools like Postman it gives JSON.