使用Node.js在Return Statement中包含标头和数据数组 [英] Including headers and data array in Return Statement with Node.js

查看:60
本文介绍了使用Node.js在Return Statement中包含标头和数据数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个lambda函数,它可以获取dynamoDB表中的所有项目,如下所示.我想知道是否有一种方法可以包括响应标头以及"scanResults"返回语句中的数组.

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.

在当前代码中,我可以包含标题或scanResults数组.我试过放两个return语句,但这是不正确的代码.有没有办法将它们结合起来?预先感谢您的帮助.

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;





};

推荐答案

您快到了,只是缺少了responseBody的不正确的ref属性:

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;
};

这篇关于使用Node.js在Return Statement中包含标头和数据数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆