简体   繁体   English

Lambda 代理的可怕的畸形响应

[英]The Dreaded Malformed Response for Lambda Proxy

I'm working on an integration with the Google Calendar API from an AWS Lambda function.我正在与来自 AWS Lambda function 的 Google 日历 API 集成。 The code works fine on my desktop as a Node.js app, but when I push the code to Lambda, I get a 502 Server error with the Malformed Response message in the log.该代码在我的桌面上作为 Node.js 应用程序运行良好,但是当我将代码推送到 Lambda 时,我收到 502 服务器错误,并在日志中显示格式错误的响应消息。 I've set up a layer with googleapi Node module (I've confirmed the versions all match) and that doesn't seem to be the issue.我已经使用 googleapi Node 模块设置了一个层(我已经确认版本都匹配),这似乎不是问题。 I'm sort of new to Lambda, so I'm stumped as to what I may have done wrong.我对 Lambda 有点陌生,所以我很困惑我可能做错了什么。

Code below:下面的代码:

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

Any ideas, etc., are greatly appreciated.非常感谢任何想法等。

Use a POST method, not a GET method and this code:使用 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM