问题
I have a lambda function that gets all items in a dynamoDB table as seen below. I am wondering if there is a way to include the response headers as well as the "scanResults" array in the return statement.
In my current code I can either include the headers or the scanResults array. I have tried putting two return statements but that is incorrect code. Is there a way to combine them? Thanks in advance for any help.
'use strict';
const AWS = require('aws-sdk');
exports.handler = async (event, context) => {
const documentClient = new AWS.DynamoDB.DocumentClient();
let responseBody = '';
let statusCode = 0;
let scanResults = [];
let items;
const params = {
TableName: "Products"
};
do {
items = await documentClient.scan(params).promise();
items.Items.forEach((item) => scanResults.push(item));
params.ExclusiveStartKey = items.LastEvaluatedKey;
} while(typeof items.LastEvaluatedKey != "undefined");
responseBody = JSON.stringify(items.Items);
statusCode = 200;
//return scanResults;
const response = {
statusCode: statusCode,
headers: {
"Content-Type": "application/json",
"access-control-allow-origin": "*"
},
body: responseBody
};
return response;
};
回答1:
You are almost there, just missing an incorrect ref property of responseBody :
'use strict';
const AWS = require('aws-sdk');
const documentClient = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event, context) => {
let responseBody = '';
let statusCode = 0;
let scanResults = [];
let items;
const params = {
TableName: "Products"
};
do {
items = await documentClient.scan(params).promise();
scanResults = [...scanResults, ...items.Items];
params.ExclusiveStartKey = items.LastEvaluatedKey;
} while(typeof items.LastEvaluatedKey != "undefined");
responseBody = JSON.stringify(scanResults);
statusCode = 200;
const response = {
statusCode: statusCode,
headers: {
"Content-Type": "application/json",
"access-control-allow-origin": "*"
},
body: responseBody
};
return response;
};
来源:https://stackoverflow.com/questions/64868585/including-headers-and-data-array-in-return-statement-with-node-js