【问题标题】:The Dreaded Malformed Response for Lambda ProxyLambda 代理的可怕的畸形响应
【发布时间】:2021-04-03 22:58:58
【问题描述】:

我正在通过 AWS Lambda 函数与 Google Calendar API 集成。该代码作为 Node.js 应用程序在我的桌面上运行良好,但是当我将代码推送到 Lambda 时,我收到 502 服务器错误,并在日志中显示格式错误的响应消息。我已经使用 googleapi Node 模块设置了一个层(我已经确认版本都匹配),这似乎不是问题。我对 Lambda 有点陌生,所以我很困惑我可能做错了什么。

代码如下:

const { google } = require('googleapis');
const apiKey = process.env.APIKEY
const calendarId = process.env.CALENDAR_ID
const cal = google.calendar({
    version: 'v3',
    auth: apiKey
});


//--------------- Utility Functions --------------------
function lastDayInMonth(month, year) {
  const daysInMonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 ];
  return ((month == 1) && 
          (((year % 4 == 0) && (year %100 != 0)) || (year % 400 == 0))) 
          ? daysInMonth[month] + 1 
          : daysInMonth[month]
}

//------------------- handler -------------------------------
exports.handler = async (event, context, callback) => {
    
    var headers = {
        'Access-Control-Allow-Headers' : 'Content-Type, X-Amz-Date, Authorization, X.Api-Key, X-Amz-Security-Token',
        'Access-Control-Allow-Methods': 'OPTIONS,POST',
        'Access-Control-Allow-Origin': '*'
    };
    
    // Get the month, year from the search parameters
    let month, year = -1
    if (event.queryStringParameters) {
        if (event.queryStringParameters.month) {
            month = event.queryStringParameters.month;
        }
        if (event.queryStringParameters.year) {
            year = event.queryStringParameters.year;
        }
    }
    
    let response = {
        "statusCode": 500,
        "multiValueHeaders": headers,
        "body": '',
        "isBase64Encoded": false
    }
    
    // test for bad dates
    if (month == -1 || year == -1) {
        response.body = JSON.stringify('Bad dates')
        return(response)
    } else {
        // set up the call to the Google Calendar API
        const startDate = new Date(year, month, 1, 0, 0, 0).toISOString();
        const endDate = new Date(year, month, lastDayInMonth(month, year),23,59,59).toISOString();
        const userTimeZone = 'America/Los_Angeles'
        let res_parms = {
            "timeMin": startDate,
            "timeMax": endDate,
            "timeZone": userTimeZone,
            "calendarId": calendarId,
        }
        // retrieve the list of events
        cal.events.list(res_parms )
        .then((result) => {
            console.log('Call was successful')
            response.statusCode = 200
            response.body = JSON.stringify(result)
            console.log(response)
            callback(null, {"statusCode": 200, "body": JSON.stringify(result)})
        })
        .catch((e) => {
            console.log('call failed')
            response.statusCode = 500
            response.body = 'No date retrieved'
            callback(null, response);
        })
    }
};

非常感谢任何想法等。

【问题讨论】:

  • 如果您在 lambda 中测试此代码是否有效?一些测试事件对象返回什么?
  • @Marcin 我一直在使用 API GW 测试该功能。我不太清楚如何在 Lambda 中测试 HTTP GET 方法。
  • @404 感谢您的关注。在一天结束时剪切和粘贴继承。修好了。
  • 我应该澄清一下,通过修复它,我的意思是说我删除了不需要的 JSON.stringify。错误仍然存​​在...

标签: node.js amazon-web-services aws-lambda google-api


【解决方案1】:

使用 POST 方法,而不是 GET 方法和此代码:

const { google } = require('googleapis')
const apiKey = process.env.APIKEY
const calendarId = process.env.CALENDAR_ID
const cal = google.calendar({
    version: 'v3',
    auth: apiKey
})

//--------------- Utility Functions --------------------
function lastDayInMonth(month, year) {
  const daysInMonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 ];
  return ((month == 1) && 
          (((year % 4 == 0) && (year %100 != 0)) || (year % 400 == 0))) 
          ? daysInMonth[month] + 1 // account for leap year
          : daysInMonth[month]
}

//--------- Handler to call Google Calendar API ---------
exports.handler = async (event, context, callback) => {
    // retrieve the month and year
    const { month, year } = JSON.parse(event.body)
    
    // set up the headers for the response
    var headers = {
        'Access-Control-Allow-Headers' : 'Content-Type, X-Amz-Date, Authorization, X.Api-Key, X-Amz-Security-Token',
        'Access-Control-Allow-Methods': 'OPTIONS,POST',
        'Access-Control-Allow-Origin': '*'
    }
    
    // set up the base response fields
    const response = {
        "statusCode": 200,
        "headers": headers,
        "body": ''
    }
    
    // set the start date for the beginning of the of the first day of the month
    const startDate = new Date(year, month, 1, 0, 0, 0).toISOString()

    // set the start date for the end of the of the last day of the month
    const endDate = new Date(year, month, lastDayInMonth(month, year), 23, 59, 59).toISOString()
    
    // set the time zone
    const timeZone = 'Americad/Los_Angeles'
    
    // set up the parameters for the call to the Google Calendar API
    const res_params = {
        'timeMin': startDate,
        'timeMax': endDate,
        'timeZone': timeZone,
        'calendarId': calendarId,
        'singleEvents': true,
        'orderBy': 'startTime'
    }
    
    await cal.events.list(res_params)
    .then(result => {
        response.body = JSON.stringify(result)
    })
    .catch(e => {
        response.body = 'Error in retrieving events'
    })

    return response
}

【讨论】:

    猜你喜欢
    • 2018-03-16
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    相关资源
    最近更新 更多