如何编写将使用快速 API 的 Azure 函数



我有一个 azure 函数, 在索引中.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();
};

我有函数.json :

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

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

当我使用 NodeJS 本地应用程序设置时,我能够在单个模块中使用 Express 并处理许多 API 端点 这在 Azure 函数中可能吗? 或者我必须为每个端点使用不同的函数

请参阅下面的代码。我们可以将 Azure 函数用作常见的快速应用。

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 模块文档。

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

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

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

否则在 ~1 中

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

我也尝试过这个azure-function-express包,但它仍在开发中,需要大量改进。我发现的最好的软件包是Azure AWS Severless Express

包。它非常易于使用和兼容。您可以轻松地将 Express 与 azure 函数一起使用

最新更新