我有一个 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/