J. Wilshere
J. Wilshere

Reputation: 47

How to return HTML content from Azure Function

The Azure function runs, however there is no HTML output? How do I get the HTML content on localhost?

File directory

index.js

const fs = require('fs');
const path = require('path');

module.exports = async 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);
        });
    }
}

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>hello world</title>
    </head>
    <body>
        <h1>Hello world!</h1>
    </body>
</html>

Upvotes: 2

Views: 3909

Answers (1)

Hury Shen
Hury Shen

Reputation: 15754

You can use context.res = res; instead of context.done(null, res);.

Like this:

enter image description here

After request the function endpoint, we can see the result page like below screenshot:

enter image description here

Upvotes: 3

Related Questions