node.js - 如何在 Azure Functions 中进行路由?

标签 node.js azure routes azure-functions

我知道我可以像这样使用 url 参数:

"myfunction?p=one&p2=two"

并在代码中变成

request.query.p = "one";

但我更愿意像这样得到它(快速路由样式):

"myfunction/:myvalue"

并使用此网址:

/myfunction/nine

在代码中变成这样:

request.params.myvalue = "nine"

但我似乎找不到如何在 Azure Functions 中配置路由路径,有什么想法或文档吗?

最佳答案

我们在 Azure Functions 中提供了对 HTTP 触发器的路由支持。现在,您可以添加遵循 ASP.NET Web API 路由命名语法的路由属性。 (您可以直接通过 Function.json 或门户 UX 设置)

"route": "node/products/{category:alpha}/{id:guid}"

函数.json:

{
    "bindings": [
        {
            "type": "httpTrigger",
            "name": "req",
            "direction": "in",
            "methods": [ "post", "put" ],
            "route": "node/products/{category:alpha}/{id:guid}"
        },
        {
            "type": "http",
            "name": "$return",
            "direction": "out"
        },
        {
            "type": "blob",
            "name": "product",
            "direction": "out",
            "path": "samples-output/{category}/{id}"
        }
    ]
}

.NET 示例:

public static Task<HttpResponseMessage> Run(HttpRequestMessage request, string category, int? id, 
                                                TraceWriter log)
{
    if (id == null)
       return  req.CreateResponse(HttpStatusCode.OK, $"All {category} items were requested.");
    else
       return  req.CreateResponse(HttpStatusCode.OK, $"{category} item with id = {id} has been requested.");
}

NodeJS 示例:

module.exports = function (context, req) {

    var category = context.bindingData.category;
    var id = context.bindingData.id;

    if (!id) {
        context.res = {
            // status: 200, /* Defaults to 200 */
            body: "All " + category + " items were requested."
        };
    }
    else {
        context.res = {
            // status: 200, /* Defaults to 200 */
            body: category + " item with id = " + id + " was requested."
        };
    }

    context.done();
}

官方文档:https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook#url-to-trigger-the-function

<小时/>

<罢工> 如今,您必须使用 Azure API 管理之类的服务来自定义您的路线。

有一个 PR 正在进行中,旨在将自定义路由添加到 Azure Functions 本身。该团队希望它能在下一个版本中发布。 https://github.com/Azure/azure-webjobs-sdk-script/pull/490

<小时/>

注意:我是 Azure Functions 团队的 PM

关于node.js - 如何在 Azure Functions 中进行路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39430279/

相关文章:

node.js - 如何在无论如何都会被调用的链的末尾添加快速中间件(OK/FAIL 响应)?

azure - 将App_Data文件夹部署到Azure权限不足

azure - 更改 Azure AD B2C 访问 token 生命周期不起作用

javascript - Node.js Express、路由器、可选参数作为扩展

node.js - Node express 订单路线

javascript - 从多个 JSON 对象获取值

node.js - 是否有使用带有 Node 的原始 Q promise 库异步递归遍历目录的示例?

javascript - 什么时候在 Node.js 中使用 eventEmitter?

c# - 与常规配置值 "true"和 "false"相比,使用 Azure 功能管理器有什么好处

php - 在此服务器上找不到请求的 URL/practice/public/admin