简体   繁体   中英

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>

在此输入图像描述 How can I force azure to always give me a json output, regardless of the request headers?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM