首页 > 解决方案 > 为什么我的 Lambda 函数有时只写入我的 DynamoDB 表?

问题描述

目标:使用 AWS Lambda、API Gateway 和 DynamoDB 为指向相应应用商店的移动应用链接创建 URL 重定向器,例如,如果 iPhone 用户访问 URL,它应该将它们重定向到特定应用的 App Store 页面。

我已经设法让它在大多数情况下工作,但每当我在任何设备上多次调用 Lambda 函数时,它都会执行重定向,但不会将记录插入到我的 DynamoDB 表中。如果我清除浏览器数据,它将插入记录,直到下次调用该函数时不再插入。

是我的代码、我的 API 网关设置还是其他问题?或者关于如何调试问题的任何建议?

拉姆达代码:

const AWS = require("aws-sdk");
const dynamoDB = new AWS.DynamoDB({ region: "eu-west-2", apiVersion: "2012-08-10" });

exports.handler = async (event, context, callback) => {
    // Set up global redirect URL variable to be returned in the response
    var redirectURL = "https://jifflr.com/";
    
    // Set up global os variable to insert into DynamoDB
    var os = "other";
    
    // Get user agent info from event header
    const userAgent = event.headers["User-Agent"];
    
    // Change redirectURL according to user agent
    switch (true) {
        case userAgent.includes("iPhone"):
            os = "iOS";
            redirectURL = "https://apps.apple.com/gb/app/jifflr/id1434427409";
            break;
        case userAgent.includes("iPad"):
            os = "iOS";
            redirectURL = "https://apps.apple.com/gb/app/jifflr/id1434427409";
            break;
        case userAgent.includes("Android"):
            os = "android";
            redirectURL = "https://play.google.com/store/apps/details?id=uk.jifflr.app&hl=en_GB";
            break;
        default:
            break;
    }
    
    // Define response parameters
    const response = {
        statusCode: 301,
        body: JSON.stringify(os),
        headers: { Location: redirectURL }
    };
    
    // Initialise insert data
    var params = {
        TableName: "jifflr",
        ReturnConsumedCapacity: "TOTAL",
        Item: {
            "id": { S: context.awsRequestId }, 
            "os": { S: os }
        }
    };
    
    // Insert into database
    try{
        const data = await dynamoDB.putItem(params).promise();
        response.body = JSON.stringify(data);
    } catch(err){
        console.log("Error: ", err);
        response.body = JSON.stringify(err);
    }
    
    return response;
};

DynamoDB 表概览: DynamoDB 表概述

标签: amazon-web-servicesaws-lambdaamazon-dynamodbaws-api-gateway

解决方案


看来您的状态码 301 是问题所在。尝试将其更改为 302。301 是永久重定向,而 302 是临时重定向。您的浏览器正在兑现响应并知道它将被重定向,因此它不会打扰调用 api。它只是重定向。将其更改为 302 应该可以解决问题。


推荐阅读