使用CDK TypeScript Lambda导入常量设置Headers触发无效响应错误
场景说明
用CDK TypeScript构建Lambda栈并对接API Gateway,直接在返回对象内定义跨域响应头时功能正常,但将Headers提取为公共常量导入使用时,Lambda启动失败。
正常工作的代码
const res = await request<ResponseModel>(req); return { statusCode: res.status, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': true }, body: JSON.stringify(res.data) };
报错的代码示例
公共常量文件 common-headers.ts
export const CommonResponseHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': true };
Lambda函数文件 function.ts
import { CommonResponseHeaders } from '../../common/common-headers'; const res = await request<ResponseModel>(req); return { statusCode: res.status, headers: CommonResponseHeaders, body: JSON.stringify(res.data) };
CDK栈定义 stack.ts
const function = { name: 'myFunction', runtime: Runtime.NODEJS_14_X, entry: path.join(__dirname, './function.ts'), vpcSubnets: { subnetType: SubnetType.PRIVATE_WITH_EGRESS }, handler: 'handler', environment: { ...SomeDefaultVariables } } const lambda = new NodejsFunction(this, function.name, function); const functionUrl = lambda.addFunctionUrl({ authType: FunctionUrlAuthType.NONE, cors: { allowedOrigins: ['*'], } }); new CfnOutput(this, `${function.name}-FunctionUrl`, { value: functionUrl.url, });
错误信息
Invalid lambda response received: Invalid API Gateway Response Keys:
{'trace', 'errorType', 'errorMessage'} in {'errorType': 'TypeError',
'errorMessage': "Cannot read property 'trim' of undefined", 'trace':
["TypeError: Cannot read property 'trim' of undefined", ' at
Object. (/var/task/index.js:10924:40)', ' at
Module._compile (internal/modules/cjs/loader.js:1085:14)', ' at
Object.Module._extensions..js
(internal/modules/cjs/loader.js:1114:10)', ' at Module.load
(internal/modules/cjs/loader.js:950:32)', ' at
Function.Module._load (internal/modules/cjs/loader.js:790:12)', '
at Module.require (internal/modules/cjs/loader.js:974:19)', ' at
require (internal/modules/cjs/helpers.js:101:18)', ' at
_tryRequireFile (/var/runtime/UserFunction.js:72:32)', ' at _tryRequire (/var/runtime/UserFunction.js:160:20)', ' at _loadUserApp (/var/runtime/UserFunction.js:219:12)']}
解决方案
1. 修复关键字变量名错误
stack.ts中使用了JavaScript保留字function作为变量名,这会直接导致编译失败,是引发错误的核心原因之一。修改变量名:
// stack.ts const functionConfig = { // 将变量名从function改为functionConfig name: 'myFunction', runtime: Runtime.NODEJS_14_X, entry: path.join(__dirname, './function.ts'), vpcSubnets: { subnetType: SubnetType.PRIVATE_WITH_EGRESS }, handler: 'handler', environment: { ...SomeDefaultVariables } } const lambda = new NodejsFunction(this, functionConfig.name, functionConfig);
2. 统一响应头值类型
API Gateway要求响应头的值必须为字符串类型,直接定义时布尔值true会被隐式转换,但作为常量导入时可能无法自动转换。修改公共常量:
// common-headers.ts export const CommonResponseHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true' // 改为字符串类型 };
3. 验证文件导入路径
确认function.ts中../../common/common-headers的路径正确,确保common-headers.ts存在于对应目录下,避免因文件找不到导致的加载错误。
4. 清理缓存重新部署
CDK构建缓存可能导致旧代码残留,执行以下命令清理后重新部署:
cdk clean && cdk deploy
内容的提问来源于stack exchange,提问作者noamyg

