Alert This post is over a year old, some of this information may be out of date.

Returning other types of data like HTML via JavaScript Azure Functions

post

A couple of weeks ago I wrote a simple Office add-in which just added a custom add-in command. An add-in command only requires that you specify an URL to a page / HTML file to make it work. As it would be overkill to create a website for just that one file, I thought about using an HTTPTrigger Azure Function to return me the necessary HTML for my command.

As it turned out it is quite easy to return the mime type of your choice with an Azure Function. In order to do this, you must specify the content-type header for the object you want to send back as the response. Like for example: HTML is text/html, XML is text/xml, text is text/plain.

Here is an example of an HTTPTrigger function which returns HTML:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const fs = require('fs');
const path = require('path');

module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var res = {
        body: "",
        headers: {
            "Content-Type": "text/html"
        }
    };

    if (req.query.name '' (req.body && req.body.name)) {
        // Just return some HTML
        res.body = "<h1>Hello " + (req.query.name '' req.body.name) + "</h1>";

        context.done(null, res);
    } else {
        // Read an HTML file in the directory and return the contents
        fs.readFile(path.resolve(__dirname, 'index.html'), 'UTF-8', (err, htmlContent) => {
            res.body= htmlContent;
            context.done(null, res);
        });
    }
};

Info: Notice line 9 - 11 where I specified the content-type header.

Show image Sample of the HMTL output
Sample of the HMTL output

Comments

Back to top