尝试测试我的 Lambda 函数,但不断收到此错误“errorMessage”:“\”[object Object]\”不是有效的 JSON”,

问题描述 投票:0回答:1

我正在为我的 React 应用程序制作一个 lambda 函数。它实际上是一个视频流服务。用户可以使用上传按钮通过 React 应用程序上传视频。 React 应用程序中的上传按钮应触发 AWS 中的 lambda 函数,以获取 S3 BUCKET 内 putObject 的预签名 URL。我在这里做错了什么???这是我的 lambda 代码

import { S3Client, ListBucketsCommand } from "@aws-sdk/client-s3";

const bucketName = "temp-videobucket-hls";

export const handler = async (event) => {
    const body = JSON.parse(event.body);
    const { fileName, fileType } = body;

    const params = {
        Bucket: bucketName,
        Key: fileName,
        Expires: 60,
        ContentType: fileType
    };
    console.log("to check if this is actually working")
    try {
        const uploadUrl =  S3Client.getSignedUrl('putObject', params);
        return {
            statusCode: 200,
            body: JSON.stringify({ uploadUrl })
        };
    } catch (err) {
        console.error('Error generating pre-signed URL', err);
        return {
            statusCode: 500,
            body: JSON.stringify({ error: 'Failed to generate pre-signed URL' })
        };
    }
};

这是我发送来测试已部署的 lambda 函数的 api 模板

{
  "version": "2.0",
  "routeKey": "$default",
  "rawPath": "/path/to/resource",
  "rawQueryString": "parameter1=value1&parameter1=value2&parameter2=value",
  "cookies": [
    "cookie1",
    "cookie2"
  ],
  "headers": {
    "Header1": "value1",
    "Header2": "value1,value2"
  },
  "queryStringParameters": {
    "parameter1": "value1,value2",
    "parameter2": "value"
  },
  "requestContext": {
    "accountId": "123456789012",
    "apiId": "api-id",
    "authentication": {
      "clientCert": {
        "clientCertPem": "CERT_CONTENT",
        "subjectDN": "www.example.com",
        "issuerDN": "Example issuer",
        "serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1",
        "validity": {
          "notBefore": "May 28 12:30:02 2019 GMT",
          "notAfter": "Aug  5 09:36:04 2021 GMT"
        }
      }
    },
    "authorizer": {
      "jwt": {
        "claims": {
          "claim1": "value1",
          "claim2": "value2"
        },
        "scopes": [
          "scope1",
          "scope2"
        ]
      }
    },
    "domainName": "id.execute-api.us-east-1.amazonaws.com",
    "domainPrefix": "id",
    "http": {
      "method": "POST",
      "path": "/path/to/resource",
      "protocol": "HTTP/1.1",
      "sourceIp": "192.168.0.1/32",
      "userAgent": "agent"
    },
    "requestId": "id",
    "routeKey": "$default",
    "stage": "$default",
    "time": "12/Mar/2020:19:03:58 +0000",
    "timeEpoch": 1583348638390
  },
  "body": {
    "fileName": "value1.mp4",
    "fileType": "video/mp4"
  },
  "pathParameters": {
    "parameter1": "value1"
  },
  "isBase64Encoded": true,
  "stageVariables": {
    "stageVariable1": "value1",
    "stageVariable2": "value2"
  }
}

问题应该出在 body 对象内部,但请求中的所有其他值都以相同的方式写入。

该错误表明当代码尝试解析我的代码第 6 行中的 JSON 时出现问题,但我无法弄清楚为什么这个 JSON 格式不正确?

node.js json amazon-web-services amazon-s3 aws-lambda
1个回答
0
投票

通过直接使用解构 event.body 对象而不应用 json.parse 解决了问题

const {fileName, fileType} = event.body;

此外,此代码无法按预期工作。对于卡在这里的其他人,请使用以下代码获取 presignedurl。这里有一篇文章解释了这一点文章

import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const generateWebFormS3URL = async (event) => {
  try {
    let REGION = "<REGION-NAME>";
    let BUCKET = "<BUCKET-NAME>";
    let KEY = event.key;

    const client = new S3Client({ region: REGION });
    const command = new PutObjectCommand({ Bucket: BUCKET, Key: KEY });
    
    const presignedUrl = await getSignedUrl(client, command, { expiresIn: 360 });
    console.log("Presigned URL:", presignedUrl);
    
    return {
      status: "Success",
      message: presignedUrl
    };
  }
  catch (err) {
    console.error(err);
    throw new Error(err);
  }
};

© www.soinside.com 2019 - 2024. All rights reserved.