接收错误:由于配置错误而执行失败:格式错误的 Lambda 代理响应

问题描述 投票:0回答:1

我目前正在开发此 API 网关 lambda,节点运行时升级到 Nodejs 18.x,并面临错误:由于配置错误而执行失败:格式错误的 Lambda 代理响应。我在下面提供代码:

任何人都可以帮我解决这个问题,因为我一直在尝试但找不到特定的解决方案。 当我尝试打印事件时,大多数字段都为空。

import needle = require("needle");
const qs = require("querystring");

"use strict";

exports.endpoint = async (event: any, context: any, callback: any) => {
const response = {
    statusCode: 500,
    body: JSON.stringify({ error: { errorCode: 500, errorMessage: "Internal Server Error - Try after sometime" } }),
    headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "POST, GET",
        "Access-Control-Allow-Credentials": true, // Required for cookies, authorization headers with HTTPS
        "X-XSS-Protection": "1; mode=block",
        "X-Frame-Options": "DENY",
        "X-Content-Type-Options": "nosniff",
        "Strict-Transport-Security": "max-age=31536000;",
        "Cache-Control": "no-cache, no-store, must-revalidate"
    }
};
context.callbackWaitsForEmptyEventLoop = false;
const options = {
method: event.httpMethod,
headers: {
    "Content-Type": "application/json"
}
};
options.headers += event.headers;
if (event.queryStringParameters && Object.keys(event.queryStringParameters).length > 0) { 
const queryParamsString = qs.stringify(event.queryStringParameters);
if (queryParamsString) {
    event.path += `?${queryParamsString}`;
}

}
console.log("Received Event:", JSON.stringify(event));
const URL = `${process.env.routing_eks_host}:${process.env.routing_eks_port}${event.path}`;
if (event && event.path) {
    console.log(`${URL}`)
}else{
console.error("Event or event.path is undefined");
}
await needle(event.httpMethod, URL, event.body, options)
.then((resp: any) => {
    console.log(`URL response code is ---> ${resp.statusCode}`);
    response.body = JSON.stringify(resp.body);
    response.headers = resp.headers;
    response.statusCode = (resp.statusCode as any);
    console.debug(`STATUS CODES FOR Response ${response.statusCode}`);
    context.succeed(response);
})
.catch((error) => {
console.error(`Error when calling API ---> ${error.message}`);
context.fail(error);
});

};

javascript node.js typescript aws-lambda aws-api-gateway
1个回答
0
投票

我想出了一个解决方案。 对于发送到 API 网关的特定标头,它们采用列表的形式。 API网关不接受列表形式的标头,仅接受JSON。

我应用的解决方案是删除以下行:

// response.headers = resp.headers;

这里:

await needle(event.httpMethod, URL, event.body, options)
.then((resp: any) => {
    console.log(`URL response code is ---> ${resp.statusCode}`);
    response.body = JSON.stringify(resp.body);
        //REMOVED THIS LINE => response.headers = resp.headers;
    response.statusCode = (resp.statusCode as any);
    console.debug(`STATUS CODES FOR Response ${response.statusCode}`);
    context.succeed(response);
})
© www.soinside.com 2019 - 2024. All rights reserved.