Azure函数可以返回XML吗?

Mar*_*ker 4 xml azure twilio azure-functions

寻找从Azure函数返回XML的Node.js示例.我下面的代码返回xml的字符串,但响应Content-Type设置为text/plain; charset = utf-8而不是text/xml; 字符集= utf-8的

index.js

module.exports = function(context, req) {
    var xml = '<?xml version="1.0" encoding="UTF-8"?><Response><Say>Azure functions!</Say></Response>';

    context.res = {
        contentType: 'text/xml',
        body: xml
    };

    context.done();
};
Run Code Online (Sandbox Code Playgroud)

这是绑定.

function.json

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ],
  "disabled": false
}
Run Code Online (Sandbox Code Playgroud)

Fab*_*nte 7

标记,

绝对!您很接近,但您可以在此处看到如何在响应中设置内容类型的示例.

还有一个解决方案,下一个版本将启用正确的内容协商,这将消除在许多情况下明确设置该内容的需要.

  • 请参阅https://github.com/Azure/azure-webjobs-sdk-script/issues/965 - 需要在响应中添加`isRaw:true`. (2认同)

Dou*_*oug 7

为了使法比奥的答案更完整,以下将是更新后的代码:

module.exports = function(context, req) {
    var xml = '<?xml version="1.0" encoding="UTF-8"?><Response><Say>Azure functions!</Say></Response>';

    context.res = {
        "headers" : { 
            "Content-Type" : 'text/xml'
        },
        "body": xml,
        "isRaw" : true
    };

    context.done();
};
Run Code Online (Sandbox Code Playgroud)

您不需要更改 function.json。

“headers”块可用于设置您想要返回的任何标题。请注意,如果您在 Function App 的设置中设置了任何内容来设置 CORS 数据,则任何与 CORS 相关的标头都将被覆盖。您要么必须在功能应用设置中设置 CORS 数据,要么在代码中手动处理 CORS。

将“isRaw”设置为 true 是必需的,这样 Azure 函数就不会试图比您更聪明,并且 XML 对您已经编码的数据进行编码。

仅供参考,根据我的经验,Azure Functions 正在积极开发并经常更改。因此,如果您遇到问题,或者此代码不再有效,那么您最好的选择;是在 Github 上搜索/打开一个问题。