解析节点js

时间:2019-08-22 12:59:57

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

我正在尝试将图像从AWS lambda函数上传到S3。为此,我遵循了本教程-link。我使用API​​网关创建了一个发布API,并在lambda中编写了nodejs代码以将图像发布到S3。但是在尝试测试API时,我从API网关中得到了错误提示。

"errorType": "TypeError [ERR_INVALID_ARG_TYPE]",
"errorMessage": "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type undefined",
"code": "ERR_INVALID_ARG_TYPE",
"stack": [
    "TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type undefined",
    "    at Function.from (buffer.js:207:11)",
    "    at Runtime.exports.handler (/var/task/index.js:17:32)",
    "    at Runtime.handleOnce (/var/runtime/Runtime.js:63:25)",
    "    at process._tickCallback (internal/process/next_tick.js:68:7)"

我的lambda代码如下所示:-

const AWS = require('aws-sdk');
//*/ get reference to S3 client 
var s3 = new AWS.S3();


exports.handler = (event, context, callback) => {


     let encodedImage =JSON.parse(event.body).user_avatar;
     let decodedImage = Buffer.from(encodedImage, 'base64');
     var filePath = "avatars/" + event.queryStringParameters.username + ".jpg"
     var params = {
       "Body": decodedImage,
       "Bucket": "find-my-mate-hasangi",
       "Key": filePath  
    };
    s3.upload(params, function(err, data){
       if(err) {
           callback(err, null);
       } else {
           let response = {
        "statusCode": 200,
        "headers": {
            "my_header": "my_value"
        },
        "body": JSON.stringify(data),
        "isBase64Encoded": false
    };
           callback(null, response);
    }
    });

};

我在下面的行中出现错误:-

 let decodedImage = Buffer.from(encodedImage, 'base64');

我正在从API网关传递到正文以下:-

{
  "body": {
    "user_avatar": "asas"
  }
}
  • 更新:在评论中提出建议后,我尝试进行一些调试
console.log( event.body);         // Output: { "body": { "user_avatar": "Hi There!" } }
console.log( JSON.parse(event.body)); // Output: { body: { user_avatar: 'Hi There' } } 
console.log( event.body.user_avatar);               // Output: undefined
console.log( JSON.parse(event.body).user_avatar);   // Output: undefined

代码是用Node JS v6.10编写的,在lambda中不再可用。所以我正在使用Node JSv10.x。可能是错误的原因吗?任何人都知道如何解决该错误。

1 个答案:

答案 0 :(得分:1)

您传递的所有数据都保存在event.body中。由于您传递的对象也是从body开始的,因此您应该这样访问它:

JSON.parse(event.body).body.user_avatar