提问者:小点点

正确地将路径参数发送到AWS Lambda NodeJS函数调用从AWS控制台工作,但从Browser/Postman不工作


我有一个NodeJS lambda函数,当从AWS控制台进行测试时可以工作,但当从浏览器或邮递员调用时返回“无法读取未定义的属性'id'”

这是我在从AWS控制台测试函数时用作测试事件的值:

{
  "pathParameters": {
    "id": "gamuda"
  }
}

我添加了console.log来查看'event'的值,正如我在其他文章中所建议的那样,并注意到当从Browser/Postman调用该值时,该值没有被读取。

2020-06-22T12:17:24.096Z 37f76d74-ef02-401e-89a6-c00eedcf56b3 INFO {} 

如何才能正确读取值? 下面是我的代码:const id=event.pathparameters.id;

module.exports.exportContactsByClientID = (event, context, callback) => {
  console.log(event);
  const id = event.pathParameters.id;
  // const id = 'mkh';
  
  const params = {
    TableName: contactsTable,
    IndexName: "client_code-created_at_local-index",
    KeyConditionExpression: "client_code = :v_ID",
    ExpressionAttributeValues: {
      ":v_ID": id,
    },
    ProjectionExpression: "client_code, created_at, contact_name, age, phone, email, dsr_ratio, max_eligibility, selected_banks"
  };

return db.query(params)
.promise()
.then((res) => {
  // console.log(res);
  const items = res.Items;
  // Headers + Columns
  worksheet.cell(1, 1).string('Client').style({font: {bold: true}});
  worksheet.cell(1, 2).string('Name').style({font: {bold: true}});
  worksheet.cell(1, 3).string('Age').style({font: {bold: true}});
  worksheet.cell(1, 4).string('Email').style({font: {bold: true}});
  worksheet.cell(1, 5).string('Phone').style({font: {bold: true}});
  worksheet.cell(1, 6).string('DSR Ratio').style({font: {bold: true}});
  worksheet.cell(1, 7).string('Max Eligibility').style({font: {bold: true}});
  // Rows
  // items.sort((a, b) => (a.date > b.date) ? -1 : 1);
  items.forEach((item, i) => {
    console.log(item.contact_name);
    worksheet.cell(i + 2, 1).string(item.client_code);
    worksheet.cell(i + 2, 2).string(item.contact_name);
    worksheet.cell(i + 2, 3).string(item.age);
    worksheet.cell(i + 2, 4).string(item.email);
    worksheet.cell(i + 2, 5).string(item.phone);
    worksheet.cell(i + 2, 6).string(item.dsr_ratio);
    worksheet.cell(i + 2, 7).string(item.max_eligibility);
  });
  console.log(contactsBucket);
  console.log(id);
  return workbook.writeToBuffer().then(buffer => {
    console.log('inside writetoubgger')
    var params = {
      Bucket: contactsBucket,
      Key: `contacts/${id}.xlsx`,
      Body: buffer,
      ACL: 'public-read'
    }
    // S3.upload(params, function(err, data) {
    //   if (err) {
    //     console.log(err, err.stack);
    //   } else {
    //     // callback(null, response(200, res));
    //     callback(null, response(200, res));
    //   }
    // });
    return S3.upload(params).promise().then(data => {
      callback(null, response(200, res));
});
  })
})
.catch((err) => callback(null, response(err.statusCode, err)));
};

当按id获取联系人时,我在读取id时使用了类似的方法,这个函数工作得很好:

module.exports.getContactsByClientID = (event, context, callback) => {
  const id = event.pathParameters.id.toLowerCase();
  const newDt = new Date();
  const filterDt = new Date(newDt.getTime() - (newDt.getTimezoneOffset() * 60000 )).toISOString().split("T")[0];

  var params = {
    TableName: contactsTable,
    IndexName: "client_code-created_at_local-index",
    KeyConditionExpression: "client_code = :v_ID AND created_at_local = :v_created",
    ExpressionAttributeValues: {
      ":v_ID": id,
      ":v_created": filterDt
    },
    ProjectionExpression: "client_code, contact_name, age, phone, email, dsr_ratio, max_eligibility, selected_banks"
  };

return db.query(params)
.promise()
.then((res) => {
  console.log(res);
  callback(null, response(200, res));
})
.catch((err) => callback(null, response(err.statusCode, err)));
};

无服务器。yml:

service: mhub-dsr-calculator-api

custom:
  allowed-headers:
      - Content-Type
      - Authorization
      - X-Api-Token
      - X-Origin
      - X-Amz-Date
      - X-Amz-Security-Token
  settings:
    CONTACTS_TABLE: dsrcalculator-contacts-dev
    CONTACTS_BUCKET: mhub-dsrcalculator-contacts

provider:
  name: aws
  runtime: nodejs12.x
  environment: ${self:custom.settings}
  region: ap-southeast-1 
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - dynamodb:DescribeTable
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
        - dynamodb:Query
      Resource:
        - "arn:aws:dynamodb:${self:provider.region}:*:table/${self:custom.settings.CONTACTS_TABLE}"
    - Effect: "Allow"
      Action:
        - dynamodb:Query
      Resource:
        - "arn:aws:dynamodb:${self:provider.region}:*:table/${self:custom.settings.CONTACTS_TABLE}/index/client_code-created_at_local-index"
    - Effect: "Allow"
      Action:
       - "s3:*"
      Resource: 
       - "arn:aws:s3:::${self:custom.settings.CONTACTS_BUCKET}/*"

functions:
  createPost:
    handler: handler.createContact
    events:
    - http:
        path: /contact
        method: post
        cors: true
  updatePost:
    handler: handler.updateContact
    events:
    - http:
        path: /contact/{id}
        method: put
        cors: true
  getAllPosts:
    handler: handler.getAllContacts
    events:
    - http:
        path: /contacts
        method: get
        cors: true
  getContactsByClientID:
    handler: handler.getContactsByClientID
    events:
    - http:
        path: /contacts/{id}
        method: get
        cors: true
  exportContactsByClientID:
    handler: handler.exportContactsByClientID
    events:
    - http:
        path: /export/{id}
        method: get
        cors: true

resources:
  Resources:
    PostsTable:
      Type: AWS::DynamoDB::Table
      Properties:
        AttributeDefinitions:
        - AttributeName: "id"
          AttributeType: "S"
        - AttributeName: "client_code"
          AttributeType: "S"
        - AttributeName: "created_at_local"
          AttributeType: "S"
        KeySchema:
        - AttributeName: "id"
          KeyType: "HASH"
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:custom.settings.CONTACTS_TABLE}
    

我已经忙了一整天了,可能错过了一些愚蠢的东西:(如有任何提示和指导,将不胜感激。


共1个答案

匿名用户

我的问题与API网关的设置有关。 以前export/{id}没有选中选项“Use Lambda Proxy Integration”(因为我正在测试一些东西)。

正如指南所说的,需要对此进行检查,以便我们的请求细节将在事件上可用。

还有一个问题--为什么我在AWS控制台上的测试没有失败。