为何我的Azure Function获取到的请求头始终为空?
请求头在Azure Function中始终为空的问题
我编写了一个简单的Azure Function,目的是查看请求头信息,供另一个开发中的端点使用:
const { app } = require("@azure/functions"); async function download(request, context) { return { status: 200, jsonBody: { headers: request.headers, context: context } }; } app.http('download', { route: "download", methods: ['GET'], authLevel: 'anonymous', handler: download }); module.exports = download;
我的function.json配置如下:
{ "bindings": [ { "dataType": "binary", "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get" ], "route": "download" }, { "type": "http", "direction": "out", "name": "res" } ] }
但无论本地通过func start运行,还是部署到云端,返回的请求头始终是空对象:
{ "headers": {}, "context": {...} }
补充其他配置信息:
package.json:
{ "name": "functions", "version": "1.0.0", "description": "A test", "main": "src/**/*.js", "scripts": { "start": "func start", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "UNLICENSED", "dependencies": { "@azure/functions": "^4.0.1", "@azure/storage-blob": "^12.16.0" }, "devDependencies": { "azure-functions-core-tools": "latest" } }
host.json:
{ "version": "2.0", "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true } } }, "extensionBundle": { "id": "Microsoft.Azure.Functions.ExtensionBundle", "version": "[4.*, 5.0.0)" } }
local.settings.json:
{ "IsEncrypted": false, "Values": { "FUNCTIONS_WORKER_RUNTIME": "node", "AzureWebJobsFeatureFlags": "EnableWorkerIndexing", "AzureWebJobsStorage": "" } }
问题原因及修复方案
核心原因
你混用了v4版本的编程式绑定模型和旧版本的声明式function.json绑定,两者的配置逻辑冲突,导致请求对象无法正确解析请求头。
修复步骤
删除
function.json文件
v4版本的Node.js Azure Functions采用全编程式配置,所有触发器规则通过代码中的app.http定义,手动维护function.json会引发配置冲突,删除后即可消除干扰。验证请求头获取逻辑
代码中request.headers的写法符合v4模型规范,删除function.json后,重启本地服务(func start),发送带自定义头的请求测试,比如:curl -H "X-Test-Header: demo-value" http://localhost:7071/api/download此时返回的JSON中应能正常显示请求头信息。
兼容旧版本的备选方案
如果必须保留function.json,则需要切换到旧版编程模式:- 删除代码中的
app.http配置块 - 修改handler的参数为
(context, req),通过req.headers获取请求头
- 删除代码中的
内容的提问来源于stack exchange,提问作者juan_julian_reveira
相关产品推荐
相关产品推荐

