使用aws-sdk将AWS Lambda调用到React页面

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

我在 React 页面中执行了这个简单的表单:

import React from 'react';
import { Link } from 'react-router-dom';
import {LambdaClient, InvokeCommand, LogType} from "@aws-sdk/client-lambda"; // ES Modules import

const FooterOne = ({ footerLight, style, footerGradient }) => {

  const invoke = async (funcName, payload) => {
    const client = new LambdaClient({});
    const command = new InvokeCommand({
      FunctionName: funcName,
      Payload: JSON.stringify(payload),
      LogType: LogType.Tail,
    });

    const { Payload, LogResult } = await client.send(command);
    const result = Buffer.from(Payload).toString();
    const logs = Buffer.from(LogResult, "base64").toString();
    return { logs, result };
  };
   

  return (
      <>
        <form>
          <input
              type='text'
              className='input-newsletter form-control me-2'
              placeholder='Enter your email'
              name='email'
              required=''
              autoComplete='off'
          />
          <input
              type='submit'
              value='Subscribe'
              data-wait='Please wait...'
          />
        </form>
      </>
  );
};

export default FooterOne;

将 Lambda 代码写入 AWS Lambda:

export const handler = async (event) => {
  // TODO implement
  const response = {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda!'),
  };
  return response;
};

您知道当我使用 JavaScript 提交这个简单表单时如何调用 AWS Lambda 代码吗

aws-sdk

javascript reactjs amazon-web-services aws-sdk aws-sdk-js
1个回答
0
投票

通过将函数传递给表单标签来监听表单上的 onSubmit 事件

<form onSubmit={handleSubmit}>

当您在按钮中添加

type: submit
时,当有人单击该按钮时,表单提交事件将在表单上触发。

你可以像这样编写handleSubmit来调用lambda

 const handleSubmit = async (e) => {
    e.preventDefault();

    // Validate and process the form data as needed
    const payload = { email: email }; // Customize this payload based on your Lambda function's requirements

    // Replace 'YourLambdaFunctionName' with the actual name of your Lambda function
    const { logs, result } = await invokeLambda('YourLambdaFunctionName', payload);

    // Handle the Lambda function response as needed
    console.log('Logs:', logs);
    console.log('Result:', result);
  };
© www.soinside.com 2019 - 2024. All rights reserved.