node.js - 如何编写使用express api的azure函数

标签 node.js azure azure-functions

我有一个 azure 的功能, 在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函数中可能吗?或者我必须为每个端点使用不同的函数

最佳答案

请参阅下面的代码。我们可以将Azure function当做一个普通的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);
如果 azure-function-express

module.exports = function (context, req)context.done() 不再有用正在使用中。如果您想使用其他上下文方法,请使用 req.context 代替。请参阅azure-function-express module doc .

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

如果您的函数运行时约为 2(测试版)。

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

大约 1 内的其他内容

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

关于node.js - 如何编写使用express api的azure函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52228045/

相关文章:

asp.net - 如何将 Visual Studio for Mac 项目连接到 Azure Data Studio 数据库?

Azure 函数 Linux 消费计划位数

azure - 当 WEBSITE_RUN_FROM_PACKAGE 的内容发生更改时,如何重新启动 Azure Functions?

node.js - 如何使用发布请求向 MLab 添加新用户?

node.js - node-postgres 获取错误连接 ECONNREFUSED

c# - ASP.NET Core错误开发模式仅在Area中

sql - 如何建立从本地到 SQL Azure 数据库的安全连接字符串

Azure Functions 代理 - 路由到存储帐户

javascript - 如何使用mongoose从js输出中获取数据?

node.js - 如何在 ExpressJS 中向布局提供当前的路由或 View ?