node.js - AWS Lamda api 无法从浏览器显示语法错误
问题描述
我创建了一个简单的方法来更新 Dynamotable 项目。如果我对 lambda 函数中的值进行硬编码并从 lamda 对其进行测试,它的工作绝对正常,但问题是当我尝试从事件中添加值时,它会显示一些语法错误。
这是我的 lamda 函数
const AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-2', apiVersion: '2012-08-10'});
var docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = (event, context, callback) => {
const params = {
TableName: "Would-You-Rather",
Key:{
"QuestionID": event.QuestionID,
},
UpdateExpression: "set Would = :w, Rather = :r, wouldClick = :wC, ratherClick = :rC",
ExpressionAttributeValues:{
":w": event.Would,
":r": event.Rather,
":wC": event.wouldClick,
":rC": event.ratherClick
},
ReturnValues:"UPDATED_NEW"
};
console.log("Updating the item...");
docClient.update(params, function(err, data) {
if (err) {
console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));
}
});
};
这是我从 lamda 测试的测试事件
{
"Would": "Soap",
"Rather": "Oil",
"wouldClick": "50",
"ratherClick": "13",
"QuestionID": "16563fa7-e833-445f-a76b-a9fbaab3a301"
}
它工作正常,但是当我尝试从 codepen 运行时,它显示的语法错误是我的代码
var xhr = new XMLHttpRequest();
xhr.open('PUT', 'https://iv9803zj9d.execute-api.us-east-2.amazonaws.com/Development/would-you-rather');
xhr.onreadystatechange = function(event) {
console.log(event);
}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'allow');
xhr.send(JSON.stringify({Would: Coffe,Rather: Tea, wouldClick: 15, ratherClick: 13, QuestionID: 16563fa7-e833-445f-a76b-a9fbaab3a301}));
它显示此错误
level: "ERROR"
line: -6
message: "Uncaught SyntaxError: Unexpected token '{'"
type: "js"
解决方案
您需要将值用字符串引号括起来。正如上面的答案,您不仅需要添加字符串引号,还需要添加QuestionID
和Would
值Rather
。
像这样
{Would: "Coffe",Rather: "Tea", wouldClick: 15, ratherClick: 13, QuestionID: "16563fa7-e833-445f-a76b-a9fbaab3a301"}
所以你的整个代码看起来像这样如果已经测试并且它的工作:)
var xhr = new XMLHttpRequest();
xhr.open('PUT', 'https://iv9803zj9d.execute-api.us-east-2.amazonaws.com/Development/would-you-rather');
xhr.onreadystatechange = function(event) {
console.log(event);
}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'allow');
xhr.send(JSON.stringify({Would: "Coffe",Rather: "Tea", wouldClick: 15, ratherClick: 13, QuestionID: "16563fa7-e833-445f-a76b-a9fbaab3a301"}));
推荐阅读
- android - 如何在 MainActivity 中实现不同屏幕尺寸的两种布局
- jquery - 单击新 div 时切换另一个 div 的类。jQuery
- docker - 当组权限似乎正确时,如何修复“拨号 unix /var/run/docker.sock:连接:权限被拒绝”?
- rss - 将 RSS 提要数据存储在我自己的服务器中是否合法?
- erlang - Erlang - Mnesia 将 disc_copy 与 ram 数据同步
- angular - 域模型不起作用 - Angular 6 & core.net 2 REST with Webpack
- java - 使用 Java RegEx 全局替换分组匹配
- c - C 在缓冲区中创建额外的字节
- html - 将代码从 ASP 转换为 ASP.NET
- mysql - 未定义变量:mysql whereNotIn