我创建了一个表单来在我的Web应用程序中添加插槽,我在API网关中为我的路由创建了一个lambda授权程序。
API路由在postman和lambda authorizer中是有效的。但是一旦我把它连接到前端,我就得到了错误,我不知道如何解决。
控制台错误
CORS配置
添加插槽和验证用户访问令牌的Javascript代码
function addSlots() {
var response = "";
var jsonData = new Object();
jsonData.restaurant_name_date_time = document.getElementById("date_time_slot").value;
jsonData.number_of_pax = document.getElementById("number_of_pax_2").value;
jsonData.restaurant_name = document.getElementById("restaurant_name_slot").value;
// validate the access token
var access_token = document.getElementById("access_token").value;
var request = new XMLHttpRequest();
request.open("POST", "https://aba3bnzddd.execute-api.us-east-1.amazonaws.com/slots", true);
request.setRequestHeader("Authorization", "Bearer " + access_token);
request.onload = function () {
response = JSON.parse(request.responseText);
console.log(response)
if (response.message == "slot added") {
alert('Congrats! You have succesfully added a slot');
} else if (response.message == "forbidden") {
alert('Invalid token. Please enter a valid access token.');
} else {
alert('Error. Unable to add slot.');
}
};
request.send(JSON.stringify(jsonData));
}
Lambda授权人代码
import json
def lambda_handler(event, context):
if event['headers']['authorization'] == 'secretcode':
response = {
"isAuthorized": True,
"context": {
"anyotherparam": "values"
}
}
return response
else:
response = {
"isAuthorized": False,
"context": {
"anyotherparam": "values"
}
}
return response
1条答案
按热度按时间2vuwiymt1#
尝试使用在Lambda函数中运行的您自己的代码返回CORS标头。例如,类似于以下内容: