如何在使用Node.js的AWS Lambda函数内调用REST API

20

我已经创建了 AWS Lambda 函数。想在我的 Lambda 函数中使用 REST API 调用。是否有关于如何使用 Node.js 将其连接到 REST API 的参考文献?


你只需要忘记“lambda函数”,并使用Node.js调用REST API。 - hoangdv
我是Node.js的新手,是否有可用于使用ngrok调用REST API的示例? - praveen Dp
1
你解决了这个问题吗?如果是,请将其更新为您的答案。我也在尝试实现相同的功能。 - Sreejith Sree
5个回答

10

const https = require('https')

// data for the body you want to send.
const data = JSON.stringify({
  todo: 'Cook dinner.'
});

const options = {
  hostname: 'yourapihost.com',
  port: 443,
  path: '/todos',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  },
};

const response = await doRequest(options, data);
console.log("response", JSON.stringify(response));

/**
 * Do a request with options provided.
 *
 * @param {Object} options
 * @param {Object} data
 * @return {Promise} a promise of request
 */
function doRequest(options, data) {
  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      res.setEncoding("utf8");
      let responseBody = "";

      res.on("data", (chunk) => {
        responseBody += chunk;
      });

      res.on("end", () => {
        resolve(JSON.parse(responseBody));
      });
    });

    req.on("error", (err) => {
      reject(err);
    });

    req.write(data);
    req.end();
  });
}


3

如果你想在Lambda函数中调用REST API,可以使用request包:

通过npm安装request包:https://www.npmjs.com/package/request

然后在Lambda函数中尝试使用以下方法调用REST API:

    var req = require('request');
    const params = {
        url: 'API_REST_URL',
        headers: { 'Content-Type': 'application/json' },
        json: JSON.parse({ id: 1})
    };
    req.post(params, function(err, res, body) {
        if(err){
            console.log('------error------', err);
        } else{
            console.log('------success--------', body);
        }
    });

我在Lambda中尝试了这个,但对我来说不起作用。而同样的REST API在Postman和Python脚本中也能工作。 - Avinash Dalvi
我们如何使用它来传递POST API的body数据?另外,我们如何解析服务的响应? - Sreejith Sree

1
const superagent = require('superagent');

exports.handler =  async(event) => {
    return await startPoint();  // use promise function for api 
}


function startPoint(){
    return new Promise(function(resolve,reject){
    superagent
    .get(apiEndPoint)
    .end((err, res) => {
        ...



       });
    })
}

0
AWS Lambda现在支持Node.js 18,它支持全局的fetch方法,你现在可以像这样轻松调用REST API端点。
// index.mjs 

export const handler = async(event) => {
    
    const res = await fetch('https://nodejs.org/api/documentation.json');
    if (res.ok) {
      const data = await res.json();
      console.log(data);
    }

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

-4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接