【问题标题】:Using aws-sdk with amplify and React将 aws-sdk 与 amplify 和 React 一起使用
【发布时间】:2019-04-16 20:51:31
【问题描述】:

我在使用 Amplify 构建的 React 应用程序中使用适用于 Javascript 的 AWS 开发工具包时遇到问题。在成功将图像上传到 S3 后,我正在尝试写入 DynamoDB 表。图片上传当前有效,但写入测试 DynamoDB 表的 SDK 方法无效。

import React, { Component } from 'react';
import { Auth } from 'aws-amplify'
import { withAuthenticator } from 'aws-amplify-react'
import { Storage } from 'aws-amplify';
const aws = require('aws-sdk'); //"^2.2.41"
    handleSubmit = (event) => {
        event.preventDefault();
        if (this.state.file == null) {
            alert("File Not Chosen")
        }
        else {     
        const file = this.state.file;
        Storage.put(this.state.name, file, {
            contentType: 'image',
            bucket:'myapp-20181030214040-deployment'
        })
        .then (result => console.log(result))
        .catch(err => console.log(err));
        }

           Auth.currentCredentials()
           .then(credentials => {
             const dynamodb = new aws.DynamoDB({
               apiVersion: '2012-08-10',
               credentials: Auth.essentialCredentials(credentials)
             });
             let params = {
                Item: {
                "testKey": {
                S: "test1"
                }
                }, 
                ReturnConsumedCapacity: "TOTAL", 
                TableName: "test"
            };
            dynamodb.putItem(params, function(err, data) {
                if (err) console.log(err, err.stack); // an error occurred
                else     console.log(data);           // successful response
                /*
                data = {
                ConsumedCapacity: {
                CapacityUnits: 1, 
                TableName: "Music"
                }
                }
                */
            });
           })
    }

句柄提交的第一部分有效,直到 Storage.put,但尽管编译,DynamoDB putItem 方法似乎没有做任何事情。谁能指出我将它们一起使用的正确方向?

【问题讨论】:

    标签: javascript reactjs amazon-web-services aws-sdk aws-amplify


    【解决方案1】:

    您可以在 dynamo db api 前面使用 AppSync 或 API Gateway 之类的东西。

    你可以看看:https://github.com/aws-samples/aws-mobile-appsync-events-starter-react

    对于使用 AppSync 和 GraphQL(由 dynamodb 支持)的示例

    或:https://github.com/aws-samples/aws-mobile-react-sample

    它使用 API Gateway 调用 REST api 来查询 dynamodb。这可以通过首先调用 amplify add storage 并选择 NoSql Database 并使用 amplify 设置您的表然后调用 amplify add api 来轻松完成它会添加一堆文件作为您的后端,您可以调用这些文件来调用您的发电机表。

    但在现有代码中,您可能还想尝试使用带有正确 import 语句的 sdk 进行反应,如 import AWS from 'aws-sdk'; 以查看它是否有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-11
      • 2017-09-18
      • 2016-08-30
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      相关资源
      最近更新 更多