Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force Azure function to output JSON to browsers

I have an azure function setup with this source:

module.exports = function(context, req) {
    //this is the entire source, seriously
    context.done(null, {favoriteNumber : 3});
};

When I use a tool like postman to visit it I get a nice JSON output, exactly like I want:

{
  "favoriteNumber": 3
}

The problem is when I visit it in a browser (chrome, firefox, etc) I see:

<ArrayOfKeyValueOfstringanyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"><KeyValueOfstringanyType><Key>favoriteNumber</Key><Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema" i:type="d3p1:int">3</Value></KeyValueOfstringanyType></ArrayOfKeyValueOfstringanyType>

enter image description here How can I force azure to always give me a json output, regardless of the request headers?

like image 418
Keatinge Avatar asked Jan 04 '23 07:01

Keatinge


1 Answers

Have you tried setting the response object's Content-Type explicitly to application\json ?

module.exports = function(context, req) {
    res = {
        body: { favoriteNumber : 3},
        headers: {
            'Content-Type': 'application/json'
        }
    };

context.done(null, res);
};

By default, Functions are configured for content negotiation. When you call your function, Chrome is sending a header like

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

so, it's asking for XML and it gets it back.

like image 96
Shiva Avatar answered Jan 07 '23 11:01

Shiva