【问题标题】:How to write azure functions which will use express api如何编写将使用 express api 的 azure 函数
【发布时间】:2020-12-30 13:22:12
【问题描述】:

我有一个天蓝色的功能, 在 index.js 我有以下代码

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

我有function.json:

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

我的 azure 函数中有上述文件,但如果我到达 api 端点,我将无法获得任何输出,我只是一个空白页。 我必须使用 express 来处理许多其他端点有什么办法可以在 azure 函数中处理。

当我使用 nodejs 本地应用程序设置时,我可以在单个模块中使用 express 和处理许多 api 端点,这在 azure 函数中是否可行?或者我必须为每个端点使用不同的功能

【问题讨论】:

    标签: node.js azure azure-functions


    【解决方案1】:

    见下面的代码。我们可以将 Azure 函数用作普通的 express 应用。

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

    如果azure-function-express 正在使用,module.exports = function (context, req)context.done() 将不再有用。如果要使用其他上下文方法,请改用 req.context 。见azure-function-express module doc

    此外,Azure 函数默认在路由中有一个前缀“api”,如果您不需要它(如上面的代码),请将其更改为清空 host.json

    如果您的函数运行时为 ~2(beta)。

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

    ~1 中的其他内容

    {
        "http": {
            "routePrefix": ""
        }
    }
    

    【讨论】:

      【解决方案2】:

      我也尝试过这个 azure-function-express 包,但它仍处于开发阶段,需要大量改进。我找到的最好的包是Azure AWS Severless Express

      包。它非常易于使用和兼容。您可以轻松地使用具有 azure 功能的 Express

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-09
        • 2016-05-15
        • 2019-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多