【问题标题】:Multiple paramater based routes for an API Endoint in an Azure FunctionAzure 函数中 API 端点的多个基于参数的路由
【发布时间】:2023-01-04 11:38:27
【问题描述】:

我在 Azure 中有一个简单的函数应用程序,它以 JSON 格式返回数据。

https://myurl.com/api/symbolcountry/{id}

它接受一个 id 作为参数。它运作良好。

但是我想参数化部分网址

https://myurl.com/api/{endpoint}/{id}

我从来没有弄乱过 javascript 并且在试图弄清楚这个问题时有点发疯了。

函数.json 文件:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get"
      ],      
      "route": "symbolcountry/{id}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}

index.js 文件:

module.exports = function (context, req) {    
    const method = req.method.toLowerCase();
    var payload = null;
    var entity = "";


    switch(method) {
        case "get":
            if (req.params.id) {                
                entity = "symbolcountry"                                      
                payload = { "SymbolID": req.params.id};  
            } 
            else {                
                entity = "symbols"                
            }
            break;    
    }

}

尝试在 function.json 中添加参数无济于事。

【问题讨论】:

    标签: javascript azure-functions


    【解决方案1】:
    • 我想访问 URL 中传递的参数而不是 params 使用密钥工作 query

    您的代码将如下所示:

    
    module.exports = function (context, req) {
        const  metthod = req.method.toLowerCase();
        var payload = null;
        var entity = "";
        switch(metthod)
        {
            case "get" : if(req.query.id)
                      {
                          entity="symbolcountry";
                          payload = {
                                        "SymbolId":req.query.id 
                                    }
                      }
                      break;
        }
        context.res = {
                body = payload
            }
    
    

    上面的代码将返回有效负载

    输出 :

    如果你想通过路由传递参数,你可以参考 JOE GATT 的article

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-17
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      • 2018-06-14
      • 1970-01-01
      相关资源
      最近更新 更多