4

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?

Keatinge
  • 4,330
  • 6
  • 25
  • 44

1 Answers1

10

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.

Mikhail Shilkov
  • 34,128
  • 3
  • 68
  • 107
Shiva
  • 20,575
  • 14
  • 82
  • 112
  • 1
    Thanks so much! It works perfect, it had a syntax error so I edited to fix it. Where did you find this, I was searching around for 20+ minutes and only found answers for .net applications – Keatinge Mar 23 '17 at 20:42
  • 1
    Thank you! "By default, Functions are configured for content negotiation" Can a function be forced-configured to use JSON? I can't find that setting. – Frank Monroe Jan 19 '18 at 21:54