无法从 AWS lambda (wo VPC) 对外部服务进行 API 调用 无服务器.ymlmyFunc.js

问题描述

我将 serverless 框架与 AWS lambda (node.js) 结合使用。

lambda 使用 axios 进行两次 API 调用 - 一次 GET 和一次 POST。在本地运行该函数时,一切正常,但是当我在 AWS 中部署和运行它时,POST 请求不会发生但我没有在日志中收到任何错误消息 .

我之前看到过一些关于这个问题的问题(例如 here),他们都提到需要在 VPC 中运行的函数中定义一些东西。这个特定的功能没有配置 VPC,所以我认为这不是问题。

我还在 serverless.yml 中启用了 cors(见下文)。

任何帮助将不胜感激。

无服务器.yml

service: someservice
app: makingapps
org: orgname
frameworkVersion: '2'

provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: 11111
  httpApi:
    cors: true

functions:
  myfunc:
    handler: myfunc.myfunc
    events:
      - httpApi:
          path: /
          method: get
plugins:
  - serverless-offline

myFunc.js

const axios = require('axios');

module.exports.myFunc = async (event) => {
    async function sendEmail(number) {
        console.log('[sendingEmail] function started' ) //Shows in the logs
        const message = `The number is ${number}`
        let options = {
            method: 'POST',url: 'https://rapidprod-sendgrid-v1.p.rapidapi.com/mail/send',headers: {
                'content-type': 'application/json','x-rapidapi-key': 'key-hash','x-rapidapi-host': 'hostname.com'
            },data: {
                foo: [{'bar_key': 'bar_value'}],content: [{type: 'text/plain',value: message}]
            }
        };
        try {
            const emailResponse = await axios(options) 
            console.log(emailResponse.data); //Only shows in the log when run locally
        } catch(error) {
            console.error(error); //Doesn't show in the log
        }
    }


    const response = {
        statusCode: 200,body: null,};

    try {
      const numResponse = await axios.get('https://example.com');
      const number = numResponse.data
      console.log(number) //Shows on logs
      
      response.body = 'The current number is: ' + number;
      response.statusCode = 200;
      sendEmail(number);
      console.log('[main] after sendEmail function') //Shows in logs

    } catch (err) {
        response.body = err;
        response.statusCode = 'Error';
    } finally {
        console.log('Here is the response: ',response.body);
        return response;
    }
};

解决方法

sendMail 是一个 async 函数。你必须await

替换

sendEmail(number);
await sendEmail(number);