如何使用Node.js 10x在AWS Lambda中将发布请求发送到外部api?

时间:2019-09-15 15:51:50

标签: node.js aws-lambda

我正在尝试使用nodejs 10.x将发布请求发送到AWS Lambda中的外部api。但是我出错了

Response:
{
  "errorMessage": "Converting circular structure to JSON",
  "errorType": "TypeError",
  "stackTrace": []
}

请在下面找到代码:

const http = require('https');

exports.handler = async (event) => {
    return new Promise((resolve, reject) => {

        const req = http.request('https://jsonplaceholder.typicode.com/posts', (res) => {
            resolve(res);
        });

        req.on('error', (e) => {
          reject({error: e.message});
        });

        // send the request
        req.write('');
        req.end();
    });
};

我期望json响应如下

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
]

1 个答案:

答案 0 :(得分:1)

您正在使用http.request而不添加选项对象,而是添加URL。您应该将其替换为http.get或添加选项对象。

您还将解决http请求的响应,而无需构建数据。如果在API网关代理集成之后使用Lambda,则应格式化响应。以下代码应该可以工作。

const http = require('https');

let getData = () => {

  return new Promise((resolve, reject) => {

    http.get('https://jsonplaceholder.typicode.com/posts', (resp) => {

      let data = '';

      resp.on('data', (chunk) => {
        data += chunk;
      });

      resp.on('end', () => {
        resolve(data);
      });
    }).on('error', (e) => {
      console.log('Error', e.message);
      reject(e);
    });
  });
};

module.exports.handler = async (event) => {

  try {
    // Data is string.
    const data = await getData();
    return {
      statusCode: 200,
      body: data
    }
  }
  catch (e) {
    console.log(e);
    return {
      statusCode: 400,
      body: e.message
    }
  }
};