如何将数据发送到API Post以供Lambda函数使用

huangapple go评论51阅读模式
英文:

How to send data to API Post to be used by Lambda Function

问题

I'm trying to post my customer name using fetch, in an async function.

async function ExecuteEC2(customer) {
    const response = await fetch(
        'https:api',
        {
            method: 'POST',
            body: {
                Customer: customer,
            },

            success: function (response) {
                alert(response.status);
            },
            error: function () {
                alert("error with database");
            }
        }
    );

}

The function is used in my button so that when it is clicked it triggers the API.

    <button
        className="btn btn-primary bt-btn btn-size"
        type="button"
        onClick={() => {
            alert("Oh, hi " + customer);
            ExecuteEC2(customer);
        }}
    >
        Configure Ansible
    </button>
    <Modal
        showModal={showModal}
        setShowModal={setShowModal}
        devices={options.AllCSRList}
        user={user}
        customer={customer}
    />

Finally, the lambda function has been set up to read and apply the API data to our EC2. However, it doesn't show up whenever I try to grab the customer data. Where and how would I amend this to push it through the post?

import time
import json
import boto3
import urllib3
import requests
from pprint import pprint 

region = 'eu-west-2'
instance = 'i-ec2'
ec2 = boto3.client('ec2', region_name=region)

def handler(event, context):

    customer_name = event['Customer']

    
    print(customer_name)

    #boto3 client
    client = boto3.client('ec2')
    ssm = boto3.client('ssm')
    # status = client.describe_instance_status(IncludeAllInstances = True)
    # pprint(status)
    
    # response = ssm.send_command(

    #     InstanceIds=['i-ec2'],
    #     DocumentName="AWS-RunShellScript",
    #     Parameters={'commands':[
    #     "mkdir create2.txt",
    #     ]},
            
    # )
        
    # print(response)
    
    
    return {
        'statusCode': 200,
        'body': json.dumps(customer_name)
    }
英文:

I'm trying to post my customer name using fetch, in an async function.

     async function ExecuteEC2(customer) {
        const response = await fetch(
          &#39;https:api&#39;,
          {
            method: &#39;POST&#39;,
            body: {
              Customer: customer,
            },
    
            success: function (response) { 
              alert(response.status);
            },
            error: function () {
              alert(&quot;error with database&quot;);
            }
          }
        );
        
      }

The function is used in my button so that when it is clicked it triggers the API.

    &lt;button
                className=&quot;btn btn-primary bt-btn btn-size&quot;
                type=&quot;button&quot;
                onClick={() =&gt; {
                  alert(&quot;Oh, hi &quot; + customer);
                  ExecuteEC2(customer);
                }}
              &gt;
                Configure Ansible
              &lt;/button&gt;
              &lt;Modal
                showModal={showModal}
                setShowModal={setShowModal}
                devices={options.AllCSRList}
                user={user}
                customer={customer}
              /&gt;

Finally, the lambda function has been set up to read and apply the API data to our EC2. However, it doesn't show up whenever I try to grab the customer data. Where and how would I amend this to push it through the post?

    import time
    import json
    import boto3
    import urllib3
    import requests
    from pprint import pprint 
    
    region = &#39;eu-west-2&#39;
    instance = &#39;i-ec2&#39;
    ec2 = boto3.client(&#39;ec2&#39;, region_name=region)
    
    def handler(event, context):
    
        customer_name = event[&#39;Customer&#39;]
    
        
        print(customer_name)
    
        #boto3 client
        client = boto3.client(&#39;ec2&#39;)
        ssm = boto3.client(&#39;ssm&#39;)
        # status = client.describe_instance_status(IncludeAllInstances = True)
        # pprint(status)
        
        # response = ssm.send_command(
    
        #     InstanceIds=[&#39;i-ec2&#39;],
        #     DocumentName=&quot;AWS-RunShellScript&quot;,
        #     Parameters={&#39;commands&#39;:[
        #     &quot;mkdir create2.txt&quot;,
        #     ]},
                
        # )
            
        # print(response)
        
        
        return {
            &#39;statusCode&#39;: 200,
            &#39;body&#39;: json.dumps(customer_name)
        }

答案1

得分: 0

"注意:我将根据 JavaScript 版本的 Lambda 编写答案。所需翻译的部分如下:

body 属性位于事件对象的 body 属性中。

body = event["body"]

另外,body 是一个 JSON 字符串,您需要将其转换为 JSON 对象/字典。

然后

customer_name = body["Customer"]"
英文:

Note: I am writing my answer with respect to javascript version of lambda.
The post data is in the body property of the event object.

body = event[&quot;body&quot;]

Also the the body is a json string and you will have to convert it to a json/dictionary.

then

customer_name = body[&quot;Customer&quot;]

答案2

得分: 0

要解决这个问题,我不得不重新编写我的异步函数。

首先,我将该函数添加到我的API调用文件中。

async function ExecuteEC2API({ apiName, path, user, body }) {
  // 用你在API上配置的路径替换这一部分
  let jwt = user.signInUserSession.idToken.jwtToken;
  let myInit = {
    headers: { Authorization: `${jwt}` }, // 可选项
    response: true,
    queryStringParameters: body,
  };
  try {
    const response = await API.post(apiName, path, myInit);
    console.log(await response);
    return await response;
  } catch (err) {
    console.log("fetch failed", err);
  }
}

接着,我编辑了deploypage.js中的异步函数以调用所需的内容。

let ExecuteEC2 = async () => {
  let response = await ExecuteEC2API({
    apiName: ....,
    user: user,
    body: {
      method: "query",
      Key: Key,
      Customer: customer,
    },
  });
  console.log("EC2", response);
  await delay(5);
};

这似乎解决了问题!

英文:

To fix this issue I had to redo my async function.

I first added the function to my API call file.

async function ExecuteEC2API({ apiName, path, user, body }) {
  // replace this with the path you have configured on your API
  let jwt = user.signInUserSession.idToken.jwtToken;
  let myInit = {
    headers: { Authorization: `${jwt}` }, // OPTIONAL
    response: true,
    queryStringParameters: body,
  };
  try {
    const response = await API.post(apiName, path, myInit);
    console.log(await response);
    return await response;
  } catch (err) {
    console.log(&quot;fetch failed&quot;, err);
  }
}

Following this, I then edited the async function in the deploypage.js to call what was needed,

  let ExecuteEC2 = async () =&gt; {
    let response = await ExecuteEC2API({
      apiName: ....,
      user: user,
      body: {
        method: &quot;query&quot;,
        Key: Key,
        Customer: customer,
      },
    });
    console.log(&quot;EC2&quot;, response);
    await delay(5);
  };

This seemed to do the trick!

huangapple
  • 本文由 发表于 2023年3月7日 18:29:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75660782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定