最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I force Azure function to output JSON to browsers - Stack Overflow

programmeradmin4浏览0评论

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="" xmlns=""><KeyValueOfstringanyType><Key>favoriteNumber</Key><Value xmlns:d3p1="" 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?

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/2001/XMLSchema-instance" xmlns="http://schemas.microsoft./2003/10/Serialization/Arrays"><KeyValueOfstringanyType><Key>favoriteNumber</Key><Value xmlns:d3p1="http://www.w3/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?

Share Improve this question edited Mar 23, 2017 at 20:48 Keatinge asked Mar 23, 2017 at 20:28 KeatingeKeatinge 4,3216 gold badges28 silver badges44 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论