【问题标题】:Unable to post to DynamoDB using axios无法使用 axios 发布到 DynamoDB
【发布时间】:2019-07-22 22:15:29
【问题描述】:

所以我目前正在尝试使用 API Gateway 将数据发布到我的 DynamoDB。当我对其进行测试时,它会以200 状态返回 - 但我的 DynamoDB 从未更新。

这是我的 axios 发布请求:

axios.post('https://1eugzswetg.execute-api.us-west-1.amazonaws.com/beta/users', {
  email: "test@gmail.com",
  salt: "123",
  sha512: "123"
  })
  .then(res => {
    console.log(res);
  })
  .catch(err => {
    console.log(err);
  })

这是我使用该 API 网关访问的 Lambda 函数:

const AWS = require('aws-sdk');

const dynamoDb = new AWS.DynamoDB.DocumentClient({ region: 'us-west-1' });

exports.handler = async function(event, ctx, callback) {
  var params = {
    Item: {
      email: event.email,
      salt: event.salt, 
      sha512: event.sha512
    },
    TableName: 'users'
  }

  try {
    const data = await dynamoDb.put(params).promise()
    console.log({ statusCode: 200, body: { params, data }})
  } catch (err) {
    console.log(err) 
  }
}

这是我的 axios 调用后记录的内容:

{ status: 200,
  statusText: 'OK',
  headers:
   { date: 'Thu, 28 Feb 2019 02:41:01 GMT',
     'content-type': 'application/json',
     'content-length': '4',
     connection: 'close',
     'x-amzn-requestid': '49249c4f-3b02-11e9-af6d-819f17575656',
     'x-amz-apigw-id': 'VyiJmFI6SK4FgYQ=',
     'x-amzn-trace-id': 'Root=1-5c774a3d-2fc47364e1170574a6f083c4;Sampled=0' },
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'Content-Type': 'application/json;charset=utf-8',
        'User-Agent': 'axios/0.18.0',
        'Content-Length': 54 },
     method: 'post',
     url:
      'https://1eugzswetg.execute-api.us-west-1.amazonaws.com/beta/users',
     data: '{"email":"test@gmail.com","salt":"123","sha512":"123"}' },
  request:
   ClientRequest {
     domain: null,
     _events:
      { socket: [Function],
        abort: [Function],
        aborted: [Function],
        error: [Function],
        timeout: [Function],
        prefinish: [Function: requestOnPrefinish] },
     _eventsCount: 6,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     outputSize: 0,
     writable: true,
     _last: true,
     chunkedEncoding: false,
     shouldKeepAlive: false,
     useChunkedEncodingByDefault: true,
     sendDate: false,
     _removedConnection: false,
     _removedContLen: false,
     _removedTE: false,
     _contentLength: null,
     _hasBody: true,
     _trailer: '',
     finished: true,
     _headerSent: true,
     socket:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: '1eugzswetg.execute-api.us-west-1.amazonaws.com',
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 8,
        connecting: false,
        _hadError: false,
        _handle: [TLSWrap],
        _parent: null,
        _host: '1eugzswetg.execute-api.us-west-1.amazonaws.com',
        _readableState: [ReadableState],
        readable: true,
        domain: null,
        _maxListeners: undefined,
        _writableState: [WritableState],
        writable: false,
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: [TLSWrap],
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        [Symbol(res)]: [TLSWrap],
        [Symbol(asyncId)]: 7,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0,
        [Symbol(connect-options)]: [Object] },
     connection:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: '1eugzswetg.execute-api.us-west-1.amazonaws.com',
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 8,
        connecting: false,
        _hadError: false,
        _handle: [TLSWrap],
        _parent: null,
        _host: '1eugzswetg.execute-api.us-west-1.amazonaws.com',
        _readableState: [ReadableState],
        readable: true,
        domain: null,
        _maxListeners: undefined,
        _writableState: [WritableState],
        writable: false,
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: [TLSWrap],
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        [Symbol(res)]: [TLSWrap],
        [Symbol(asyncId)]: 7,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0,
        [Symbol(connect-options)]: [Object] },
     _header:
      'POST /beta/users HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/json;charset=utf-8\r\nUser-Agent: axios/0.18.0\r\nContent-Length: 54\r\nHost: 1eugzswetg.execute-api.us-west-1.amazonaws.com\r\nConnection: close\r\n\r\n',
     _onPendingData: [Function: noopPendingOutput],
     agent:
      Agent {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        defaultPort: 443,
        protocol: 'https:',
        options: [Object],
        requests: {},
        sockets: [Object],
        freeSockets: {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256,
        maxCachedSessions: 100,
        _sessionCache: [Object] },
     socketPath: undefined,
     timeout: undefined,
     method: 'POST',
     path: '/beta/users',
     _ended: true,
     res:
      IncomingMessage {
        _readableState: [ReadableState],
        readable: false,
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        socket: [TLSSocket],
        connection: [TLSSocket],
        httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers: [Object],
        rawHeaders: [Array],
        trailers: {},
        rawTrailers: [],
        aborted: false,
        upgrade: false,
        url: '',
        method: null,
        statusCode: 200,
        statusMessage: 'OK',
        client: [TLSSocket],
        _consuming: false,
        _dumped: false,
        req: [Circular],
        responseUrl:
         'https://1eugzswetg.execute-api.us-west-1.amazonaws.com/beta/users',
        redirects: [] },
     aborted: undefined,
     timeoutCb: null,
     upgradeOrConnect: false,
     parser: null,
     maxHeadersCount: null,
     _redirectable:
      Writable {
        _writableState: [WritableState],
        writable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _options: [Object],
        _redirectCount: 0,
        _redirects: [],
        _requestBodyLength: 54,
        _requestBodyBuffers: [],
        _onNativeResponse: [Function],
        _currentRequest: [Circular],
        _currentUrl:
         'https://1eugzswetg.execute-api.us-west-1.amazonaws.com/beta/users' },
     [Symbol(isCorked)]: false,
     [Symbol(outHeadersKey)]:
      { accept: [Array],
        'content-type': [Array],
        'user-agent': [Array],
        'content-length': [Array],
        host: [Array] } },
  data: null }

知道为什么我的 DynamoDB 没有更新吗?当我在 API Gateway 控制台中对其进行测试时,它可以工作。这是我在 API Gateway 控制台中测试它时发生的屏幕截图

【问题讨论】:

    标签: javascript aws-lambda amazon-dynamodb axios aws-api-gateway


    【解决方案1】:

    如果它从 API 网关控制台工作,那么它是客户端问题,还是未部署到 api 网关阶段的最新版本?

    【讨论】:

    • 我刚刚在 API 网关中重新部署 - 很确定这是客户端问题,但据我所知没有错误
    【解决方案2】:

    提示:

    • 您可以尝试 amazon cloudwatch 服务,看看它在函数内部发生了什么。

    • 您确定您的用户 (IAM) 有权限吗? Access Keys for IAM Users

    • 你必须在这个函数中返回任何类似的东西:

      export async function ping(event, context) {
          ...
          ...
          ...
          return Promise((resolve,reject) => { 
              return resolve({
                  "statusCode": 200,
                  "headers": {
                      "Content-Type": "application/json"
                  },
                  "body": null,
                  "isBase64Encoded": false
              })
          })
      }
      

    我为您准备了一个基本示例(工作)putItem 实现:

    See code

    • git 克隆
    • npm 安装
    • npm 运行部署
    • 魔法!!

    您必须查看的文件:

    • package.json(已安装所有依赖项)我使用无服务器框架
    • serverless.yml(您部署的所有配置)我也在创建一个名为“TableTest”的 dynamodb 表资源,每次部署我都会删除所有资源并再次创建。

    重要提示:您的系统中必须有 AWS 凭证文件。例如:~/.aws/credentials

    祝你好运!

    【讨论】:

    • @JorahFriendzone 请用你的 axios 客户端测试我的 apigateway。
    猜你喜欢
    • 1970-01-01
    • 2019-11-10
    • 2021-02-24
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2021-01-05
    • 2021-10-07
    • 2018-08-31
    相关资源
    最近更新 更多