amazon-web-services - 为什么我的 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;
};
解决方案
看来您的状态码 301 是问题所在。尝试将其更改为 302。301 是永久重定向,而 302 是临时重定向。您的浏览器正在兑现响应并知道它将被重定向,因此它不会打扰调用 api。它只是重定向。将其更改为 302 应该可以解决问题。
推荐阅读
- import - 使用 ANTLR 的复合文法
- python - 从 Windows shell 调用 Anaconda Python 时导入失败
- python - 如何从响应中删除 u(unicode) 并使用机器人框架在正文中替换它?
- strapi - Strapi 关系的 POST 详细信息
- .net - Azure 服务总线 - 更新锁无法正常工作
- javascript - 如何在 ReactJS 中渲染嵌套数据?
- sql-server - Active Directory 组的 SqlTableDependency 权限问题
- css - 如何修复顶部导航栏粘滞位置?
- .net-core - Raspberry Pi 4 上 Visual Studio 2019 CE 的 Dotnetcore 3.0 远程调试 - 权限不足
- ruby-on-rails - 如何在 rake 任务中读取 csv 文件