javascript - AWS Lambda HTTP POST 请求 (Node.js)

标签 javascript node.js amazon-web-services aws-lambda alexa-skills-kit

我对 AWS lambda 函数和 nodejs 比较陌生。我正在尝试使用来自以下网站的 HTTP POST 请求获取一个国家/地区 5 个城市的列表:“http://www.webservicex.net/globalweather.asmx?op=GetCitiesByCountry

我一直在搜索如何在 lambda 函数中执行 HTTP POST 请求,但我似乎找不到很好的解释。

我为 http 帖子找到的搜索:

https://www.npmjs.com/package/http-post How to make an HTTP POST request in node.js?

最佳答案

我认为不需要外部库的更简洁、更高效的方式可能是这样的:

const https = require('https');

const doPostRequest = () => {

  const data = {
    value1: 1,
    value2: 2,
  };

  return new Promise((resolve, reject) => {
    const options = {
      host: 'www.example.com',
      path: '/post/example/action',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    };
    
    //create the request object with the callback with the result
    const req = https.request(options, (res) => {
      resolve(JSON.stringify(res.statusCode));
    });

    // handle the possible errors
    req.on('error', (e) => {
      reject(e.message);
    });
    
    //do the request
    req.write(JSON.stringify(data));

    //finish the request
    req.end();
  });
};


exports.handler = async (event) => {
  await doPostRequest()
    .then(result => console.log(`Status code: ${result}`))
    .catch(err => console.error(`Error doing the request for the event: ${JSON.stringify(event)} => ${err}`));
};

此 lambda 已在以下运行时上制作和测试:Node.js 8.10Node.js 10.x 并且能够执行 HTTPS 请求,做需要导入的HTTP请求,将对象改为http:

const http = require('http');

关于javascript - AWS Lambda HTTP POST 请求 (Node.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47404325/

相关文章:

php - 你如何使用 Javascript 来复制表单域?

node.js - 通过nodemailer发送带有一些图像的html

node.js - 使用 Redis 和 Socket.io 在 Laravel 5.2 中进行事件广播

amazon-web-services - 使用 AWSSDK 激活新的 CloudFront 自动压缩

linux - 使用 "aws s3"实用程序在 S3 中获取从现在起 1 个月前的文件列表

amazon-web-services - 在 us-east-1 区域启动给定的 cloudformation 模板时出现错误。 (构建 lambda 函数收到错误)

javascript - Nightmare 测试 click() 选择器

javascript - "map of union type values to strings"的 typescript 类型?

javascript - 嵌套 promise 返回未定义

javascript - 使动态创建的 promise 按顺序执行