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

fae0ux8s  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(158)

我目前正在开发这个API网关lambda,节点运行时升级到nodejs 18.x,并面临错误:由于配置错误,执行失败:Lambda代理响应格式错误。我在下面提供代码:
任何人都可以请帮助我这一点,因为我一直在尝试,但无法找到一个特定的解决方案。当我尝试打印事件时,它将大部分字段设置为null。

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);
});

};

gzszwxb4

gzszwxb41#

我想到了一个解决办法。对于发送到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);
})

相关问题