简体   繁体   English

AWS Lambda从外部公共API获取数据(基本)

[英]AWS Lambda get data from external public API (basic)

I am trying to write a simple AWS Lambda function to retrieve data from an external public API. 我正在尝试编写一个简单的AWS Lambda函数来从外部公共API检索数据。 I have copied and pasted code from all over the internet without any luck. 我已经复制并粘贴了来自互联网的代码而没有任何运气。

I have stripped down the code to be a simple as possible to keep it simple. 我已经将代码简化为尽可能简单以保持简单。 The public API is : https://swapi.co/api/people/1/ 公共API是: https//swapi.co/api/people/1/

How can I get the data back from the public API? 如何从公共API获取数据?

const https = require('https');

exports.handler = async (event) => {

    var options = {
      method: 'GET',
      host: 'https://swapi.co/api/people/1/',

    };

     console.log('options', options);

     const req = https.request(options, (res) => {
         console.log('statusCode: ${res.statusCode}')
         console.log(JSON.stringify(res))
     });


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

The log file within the AWS editor shows: AWS编辑器中的日志文件显示:

START RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728 Version: $LATEST
2019-05-27T16:17:44.839Z    3ba3f23a-11c2-40af-b9e7-0258a6531728    INFO    options { method: 'GET', host: 'https://swapi.co/api/people/1/' }
END RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728
REPORT RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728  Duration: 305.90 ms Billed Duration: 400 ms     Memory Size: 128 MB Max Memory Used: 26 MB  

There were a few issues with your code: 您的代码存在一些问题:

The callback function passed into the handler triggers the end of the execution, or is called for you when your code exits if you don't call it yourself. 传递给处理程序的callback函数会触发执行结束,或者如果您自己不调用代码,则会在您的代码退出时为您调用。 I'm not entirely sure how this interacts with asynchronous javascript code, but it might have been causing your code to exit early that you didn't call it anywhere. 我不完全确定这与异步javascript代码如何交互,但它可能导致您的代码提前退出,而您没有在任何地方调用它。

You're using an async method, which is good practice, but your rest call isn't using it, but a callback approach. 您正在使用async方法,这是一种很好的做法,但您的休息调用不是使用它,而是使用回调方法。 This can be converted into an async call, as I show below, which makes the code a bit easier to understand. 这可以转换为异步调用,如下所示,这使代码更容易理解。

I think the biggest problem, though, is that your options are wrong. 不过,我认为最大的问题是你的options是错误的。 You don't need https at the start of the host (because it already knows the scheme) and the path can't be in the host. 您不需要在主机的开头使用https (因为它已经知道该方案)并且该路径不能在主机中。 I didn't spot this initially. 我最初没有发现这一点。

This is working for me, although you can't call JSON.stringify on the entire response, because it's a complex object, not just a model. 这对我JSON.stringify ,虽然你不能在整个响应上调用JSON.stringify ,因为它是一个复杂的对象,而不仅仅是一个模型。

const https = require('https');

exports.handler = async (event, context, callback) => {
    var options = {
        method: 'GET',
        host: 'swapi.co',
        path: '/api/people/1/',
    };
    await new Promise((resolve, reject) => {
        let request = https.request(options, response => {
            try {
                // do whatever
            } finally {
                resolve();
            }
        });
        request.on('error', (e) => reject(e));
        request.end();
    });
    callback();
};

The below code is working 以下代码正常运行

const http = require("https");

exports.handler = async(event, context, callback) => {

  var options = {
    "method": "GET",
    "hostname": "app.casejacket.com",
    "port": null,
    "path": "/api/",
    "headers": {
      "cache-control": "no-cache",
      "Content-Type": "application/json"
    }
  };

  await new Promise((resolve, reject) => {
    console.log('Promise.. ');

    var req = http.request(options, function (res) {
      var chunks = [];

      res.on("data", function (chunk) {
        chunks.push(chunk);
      });

      res.on("end", function () {
        var body = Buffer.concat(chunks);
        let result = JSON.parse(body.toString());
        console.log(body.toString());
        resolve(body.toString());
        callback(null, result)
      });
    });

    req.end();
  });

  callback();

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 aws lambda 调用外部 API 并在 lambda 函数中作为回调获取响应 - call external API from aws lambda and get respose as callback in lambda funtion 从外部静态 JSON 文件中检索数据并在 AWS Lambda 中使用 - Retrieve data from external static JSON file and use in AWS Lambda 尝试使用节点和 https 通过基本身份验证从外部 api 获取数据 - Trying to get data from external api with basic authentication using node and https AWS Lambda:如何将秘密存储到外部API? - AWS Lambda: How to store secret to external API? 使用 Lambda、API 网关和 HTTP 请求将来自 AWS RDS 的查询结果显示到公共网页 - Surfacing query results from AWS RDS to public web page using Lambda, API Gateway and HTTP requests 如何从 AWS lambda 上的 API 获得正确响应 - How to get a correct response from an API on AWS lambda AWS Lambda NodeJS HTTP请求,从API打印数据 - AWS Lambda NodeJS HTTP Request, print data from API 使用AWS api网关+ lambda + Nodejs的私有和公共IP - private and public ip using AWS api gateway + lambda + Nodejs 无法从 AWS lambda(无 VPC)对外部服务进行 API 调用 - Can't make an API call to an external service from AWS lambda (wo VPC) 如何为AWS Lambda函数建立公共API路由? - How Can I Make A Public API Route For An AWS Lambda Function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM