gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:56:09 25 4
gpt4 key购买 nike

我对 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com