首页 > 解决方案 > 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"

标签: node.jsamazon-web-servicesaws-lambdaamazon-dynamodb

解决方案


您需要将值用字符串引号括起来。正如上面的答案,您不仅需要添加字符串引号,还需要添加QuestionIDWouldRather

像这样

{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"}));

推荐阅读