Node.js Azure Function添加自定义触发参数报404错误如何解决
问题根源
你出现404的核心原因是function.json中错误配置了第二个httpTrigger类型的绑定,单个Azure Function仅允许存在1个触发类型绑定,多余的触发绑定会导致路由解析异常,直接返回404。你想要实现的自定义参数注入,不需要额外添加触发绑定,按以下方案修改即可:
解决方案
方案1:路径参数注入(适合将id放在接口路径中)
保留唯一的httpTrigger绑定,新增route字段声明路径参数即可,无需额外添加其他绑定,修改后的function.json如下:
{ "bindings": [ { "authLevel": "function", "type": "httpTrigger", "direction": "in", "name": "req", "methods": ["get", "post"], "route": "demo/{id}" }, { "type": "http", "direction": "out", "name": "res" } ], "scriptFile": "../dist/respository/index.js" }
修改后调用路径为/api/demo/123,路径中的123会自动注入到你代码里的id参数。
方案2:查询参数/请求体自动注入(适配你当前的调用方式)
保留原有httpTrigger配置,删除你新增的id对应的httpTrigger绑定,替换为普通输入绑定,通过绑定表达式自动兼容GET查询参数和POST请求体参数:
{ "bindings": [ { "authLevel": "function", "type": "httpTrigger", "direction": "in", "name": "req", "methods": ["get", "post"] }, { "name": "id", "type": "bindingExpression", "direction": "in", "expression": "coalesce(Query.id, req.body.id)" }, { "type": "http", "direction": "out", "name": "res" } ], "scriptFile": "../dist/respository/index.js" }
其中coalesce函数会依次取第一个非空值,你原有的GET传?id=123、POST传{"id":123}的调用方式都可以正常识别到id值。
可选轻量方案
如果不想调整绑定配置,也可以直接在代码中手动从请求对象取值,不需要额外添加任何绑定配置,删除你新增的id对应的httpTrigger绑定后,修改代码即可:
const httpTrigger: AzureFunction = async function ( context: Context, req: HttpRequest ): Promise<void> { const id = req.query.id || req.body.id context.log("HTTP trigger function processed a request with id.", id); context.res = { body: { id, }, contentType: "application/json", }; };
内容的提问来源于stack exchange,提问作者dorty
相关产品推荐
相关产品推荐

