首页 > 解决方案 > 为什么失败的 dynamodb 查询失败并在 localhost 上出现 cors 错误而不是实际错误?

问题描述

在我的开发环境中,我设置了 Dynamodb 的本地副本,使用 Reactjs 连接到它。我正在使用 AWS 开发工具包,特别是 Dynamodb 的查询方法来进行查询。

当查询结构正确时,它运行良好。但是,如果查询结构不佳,我会得到一个神秘的响应。Chrome 控制台给了我一个:

POST http://localhost:8000/ 400 (Bad Request)
Access to XMLHttpRequest at 'http://localhost:8000/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

其中 localhost:8000 指向本地 Dynamodb 实例, localhost:3000 指向 react 实例。

最重要的是,我没有收到专门针对我所犯错误的错误消息。例如,我可能会投影一个带有保留字的字段,然后它应该不会正常工作。但是,我预计会出现一个错误,即“保留这样的词”,而不是这个 CORS 业务。

此外,当我从节点服务器运行相同的查询时,我确实收到了正确的错误消息。这让我想知道这个问题是否与 reactjs 有关。

正如我所描述的,有什么方法可以在我的开发环境中获得正确的错误消息?谢谢。

编辑:

根据评论中的要求,这是我获取数据的一种典型方式。请注意,这是一个有效的查询,因此不会产生错误。但是,随着我的开发,这将是我会犯错误并且没有看到良好反馈的查询类型。

// define tableName, indexName

async componentDidMount() {
    // properties include an initiated docClient and organizationId

    const [posts] = await Promise.all([ // typically I will fetch more than just posts (omitted for brevity)
        new Promise((resolve, reject) => 
            this.props.docClient.query(
                {
                    TableName: tableName,
                    IndexName: indexName,
                    KeyConditionExpression: 'SortKey = :sortKey',
                    ExpressionAttributeValues: {
                        ':sortKey': this.props.organizationId + delimiter + 'POST-Date'
                    },
                    ProjectionExpression: 'chatTitle, creatorName, creatorEmail, PostId, creationTime, #text, #data, lastModifiedTime, #status, mentions, attachments, chatType, creatorType',
                    ExpressionAttributeNames: { '#text': 'text', '#status': 'status', '#data': 'Data' }
                },
                (err, data) => {
                    if (err) {
                        reject(err);
                        return;
                    }

                    resolve(data.Items);
                }
            )
        )
    ]);

    // do something with posts, etc...
}

docClient 在组件中使用:

new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'})

其中 AWS 是 aws-sdk 模块

标签: javascriptreactjsamazon-web-servicesamazon-dynamodb

解决方案


推荐阅读