Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Azure Functions return XML?

Looking for a Node.js example of returning XML from an Azure Function. The code that I have below returns the string of xml, but the response Content-Type is set to text/plain; charset=utf-8 instead of text/xml; charset=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();
};

Here are the bindings.

function.json

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ],
  "disabled": false
}
like image 516
Mark Tucker Avatar asked Nov 10 '16 22:11

Mark Tucker


Video Answer


2 Answers

Mark,

Absolutely! You were close, but you can see an example of how you can set the content type on the response here.

There's also a fix with the next release that will enable proper content negotiation, which would eliminate the need to explicitly set that content in many cases.

like image 128
Fabio Cavalcante Avatar answered Sep 22 '22 01:09

Fabio Cavalcante


To make Fabio's answer more complete, the following would be the updated code:

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();
};

You do not need to change the function.json.

The "headers" block can be used to set any headers you want to return. Please note that any CORS related headers will be overwritten if you have anything set within your Function App's settings to set CORS data. You either have to set the CORS data in the Function App Settings, OR manually handle the CORS in your code.

The "isRaw" set to true is required so that the Azure Function doesn't try to outsmart you and XML encode your already encoded data.

FYI, its been my experience that Azure Functions is actively being developed and changes often. As a result your best bet if you encounter an issue, or this code no longer works; is to search/open an issue on Github.

like image 40
Doug Avatar answered Sep 22 '22 01:09

Doug