Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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' }; 
like image 398
Chris Dellinger Avatar asked May 11 '16 03:05

Chris Dellinger


People also ask

How do you return a JSON object from a function in node JS?

Go to http://localhost:3000/multiple, you will see the following output. Go to http://localhost:3000/array, you will see the following output. Method 2 (Using HTTP interface): Although the first method is sufficient for most solutions, there is another method that uses HTTP interface by Node. js and returns JSON data.

Where is function json in Azure function?

Folder structure. The code for all the functions in a specific function app is located in a root project folder that contains a host configuration file. The host. json file contains runtime-specific configurations and is in the root folder of the function app.


1 Answers

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); }; 
like image 108
spooky Avatar answered Sep 28 '22 01:09

spooky