Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write azure functions which will use express api

I have a azure function, In index.js i have the following code

module.exports = function (context, req) {

const createHandler = require('azure-function-express').createHandler;
const app = require('express')();

app.get("/home", (req, res) => {
    const y = { "name": "name", "dob": "ddmmyyyy" }
    context.res = y
    context.done()
});
module.exports = createHandler(app);

context.done();
};

i have function.json :

    {
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "route": "{*segments}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ],
  "disabled": false
}

i have the above files in my azure function but i am not able get any output i just a blank page if i hit the api end point. i have to use express to handle many other end points is there any way to handle in azure functions.

when i use nodejs local application setup, i am able to use express and handle many api end points with in a single module is that possible in azure functions? or i have to use different functions for each end point

like image 304
Veda Vyas Avatar asked Oct 23 '25 14:10

Veda Vyas


2 Answers

See code below. We can use Azure function as a common express app.

const createHandler = require('azure-function-express').createHandler;
const app = require('express')();

app.get("/home", (req, res) => {
    res.json({ "name": "name", "dob": "ddmmyyyy" });
});

app.get("/work", (req, res) => {
    res.json({ "name": req.query.name, "dob": "ddmmyyyy" });
});

module.exports = createHandler(app);

module.exports = function (context, req) and context.done() are no longer useful if azure-function-express is in use. If you want to use other method of context, use req.context instead. See azure-function-express module doc.

Besides, Azure function has a prefix "api" in route by default, if you don't need it(like code above), change it to empty your host.json.

If your function runtime is ~2(beta).

{
  "version": "2.0",
  "extensions": {
    "http": {
        "routePrefix": ""
    }
  }
}

Else in ~1

{
    "http": {
        "routePrefix": ""
    }
}
like image 130
Jerry Liu Avatar answered Oct 26 '25 05:10

Jerry Liu


I have also use try this azure-function-express package but its still in the development and need a-lot of improvement. The best package i found is Azure AWS Severless Express

Package. Its very easy to use and compatible. You can easily use the Express with azure functions

like image 38
Sohaib Avatar answered Oct 26 '25 03:10

Sohaib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!