我将如何在AWS Lambda中返回状态代码和回复
我正在编写Lambda函数,该函数将用于向API发送测试消息。如果有错误,我将需要它来运行某些功能(例如,通过AWS消息通知我)。我想通过状态码进行简单测试。例如,如果我得到2XX,什么也不做,如果我得到4XX或5XX,请通知我,以便我可以研究问题。在测试环境中,我将主体作为XML字符串作为值传递给JSON对象。
示例Lambda测试事件
{
"data": "<xml stuff, credentials, etc"
}
这是我的职能
exports.handler = async (event, context) => {
const https = require('https');
const options = {
hostname: '',
port: 443,
path: '/target',
method: 'POST',
headers: {'Content-Type': 'application/xml'}
};
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
});
});
req.on('error', error => {
console.error(error);
});
req.write(event.data);
req.end();
};
我在Lambda中使用节点10.x,并且从lambda收到“结果成功”消息,但未记录响应状态代码。我已经用几种方法做到了,并且过去已经轻松地从Node fetch,ajax,http请求中拉出了statsCodes。我知道这可能与Lambda的环境和承诺有关。谁能帮我弄清楚如何在Lambda中记录统计代码?
回答如下:您看不到它被打印出来,因为您的函数是async
,并且https.request
使用回调方法,该方法将由Node.js工作者异步运行。事实证明,该函数将有机会在回调内执行代码之前到达其末端。
您必须promisify https.request
或使用已经可用于Promises的库,因此您可以轻松地对它们进行await
。 Axios和Request是不错的选择。
一旦选择了库-或承诺了https.request
(在我的示例中将使用axios
),您可以简单地在调用中使用await
,获取其结果并随心所欲。
const res = await axios.post('https://service-you-want-to-connect-to', {})
console.log(JSON.stringify(res)) // here you inspect the res object and decide what do to with the status code.
我将如何在AWS Lambda中返回状态代码和回复
我正在编写Lambda函数,该函数将用于向API发送测试消息。如果有错误,我将需要它来运行某些功能(例如,通过AWS消息通知我)。我想通过状态码进行简单测试。例如,如果我得到2XX,什么也不做,如果我得到4XX或5XX,请通知我,以便我可以研究问题。在测试环境中,我将主体作为XML字符串作为值传递给JSON对象。
示例Lambda测试事件
{
"data": "<xml stuff, credentials, etc"
}
这是我的职能
exports.handler = async (event, context) => {
const https = require('https');
const options = {
hostname: '',
port: 443,
path: '/target',
method: 'POST',
headers: {'Content-Type': 'application/xml'}
};
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
});
});
req.on('error', error => {
console.error(error);
});
req.write(event.data);
req.end();
};
我在Lambda中使用节点10.x,并且从lambda收到“结果成功”消息,但未记录响应状态代码。我已经用几种方法做到了,并且过去已经轻松地从Node fetch,ajax,http请求中拉出了statsCodes。我知道这可能与Lambda的环境和承诺有关。谁能帮我弄清楚如何在Lambda中记录统计代码?
回答如下:您看不到它被打印出来,因为您的函数是async
,并且https.request
使用回调方法,该方法将由Node.js工作者异步运行。事实证明,该函数将有机会在回调内执行代码之前到达其末端。
您必须promisify https.request
或使用已经可用于Promises的库,因此您可以轻松地对它们进行await
。 Axios和Request是不错的选择。
一旦选择了库-或承诺了https.request
(在我的示例中将使用axios
),您可以简单地在调用中使用await
,获取其结果并随心所欲。
const res = await axios.post('https://service-you-want-to-connect-to', {})
console.log(JSON.stringify(res)) // here you inspect the res object and decide what do to with the status code.