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
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With