Reputation: 2237
I am trying to upload an image to S3 from a AWS lambda function. For this I have followed this tutorial - link. I have created an post API using API Gateway and written nodejs code in lambda to post an image to S3. But I am getting below error from API Gateway while trying to test the 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)"
My lambda code looks like below:-
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);
}
});
};
I am getting error in below line:-
let decodedImage = Buffer.from(encodedImage, 'base64');
I am passing below body from API Gateway:-
{
"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
The code is written in Node JS v6.10 which is not available in lambda anymore. So I am using Node JS v10.x. Can it be the reason for the error? Anyone know how to resolve the error.
Upvotes: 0
Views: 2294
Reputation: 3141
All data that you pass lives in event.body
. Since you are passing object that also starts from body
, you should access it like this:
JSON.parse(event.body).body.user_avatar
Upvotes: 1