gpt4 book ai didi

node.js - 使用 AWS Lambda NodeJS 时无法返回结果

转载 作者:太空宇宙 更新时间:2023-11-04 03:12:44 24 4
gpt4 key购买 nike

我正在尝试在 AWS Lambda 上实现一个简单的 Node Js 函数来从 dynamoDB 查询数据。我将此 lambda 函数挂接到我的 API 网关,但当我访问 API url 时没有看到任何结果。

//Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'us-east-1'});

// Create DynamoDB service object
var b = new AWS.DynamoDB({apiVersion: '2012-08-10'});

var params = {
ExpressionAttributeNames: {
"#devicetimestamp": "timestamp"
},
ExpressionAttributeValues: {
':unitID': {S: 'arena-MXHGMYzBBP5F6jztnLUdCL'},
':dtimestamp' : {S: '1582920096000'}
},
KeyConditionExpression: 'id = :unitID and #devicetimestamp > :dtimestamp',
TableName: 'IoTdata2'
};

b.query(params, function(err, results) {
if (err) {
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
console.log("Query succeeded.");
console.log(JSON.stringify(results));
}
});

当我看到 console.log(JSON.stringify(results)); 的结果时,代码工作正常;当我使用事件处理程序时

//Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'us-east-1'});

// Create DynamoDB service object
var b = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {

var params = {
ExpressionAttributeNames: {
"#devicetimestamp": "timestamp"
},
ExpressionAttributeValues: {
':unitID': {S: 'arena-MXHGMYzBBP5F6jztnLUdCL'},
':dtimestamp' : {S: '1582920096000'}
},
KeyConditionExpression: 'id = :unitID and #devicetimestamp > :dtimestamp',
TableName: 'IoTdata2'
};

b.query(params, function(err, results) {
if (err) {
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
callback(err);
} else {
console.log("Query succeeded.");
console.log(JSON.stringify(results));
callback(null, results);
}
});
};

```i don't see any response in API URL.I am new to nodeJS, Any suggestions will be greatly appreciated. Thanks

最佳答案

由于您要通过 API 网关,因此您需要满足来自 lambda 的特定响应契约,请尝试这样做:

const response = {
statusCode: 200, // need a status code
body: JSON.stringify(results) // and a string body
}

callback(null, response)

这里有更多信息:TUTORIAL: Build a Hello World API with Lambda Proxy Integration - Amazon API Gateway

关于node.js - 使用 AWS Lambda NodeJS 时无法返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60478825/

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