我已经设置了API Gateway(HTTP)〉Lambda〉DynamoDB。我可以通过Postman成功地执行PUT和GET请求,但当我尝试通过浏览器执行PUT请求时,收到CORS错误。我可以通过浏览器成功地执行GET请求。
通过浏览器返回的Post请求Access to XMLHttpRequest at 'https://xxx.execute-api.eu-west-1.amazonaws.com/items' from origin 'http://localhost:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我已经在API网关上启用了CORS。自动重新部署已打开。我还手动重新部署以防万一。
我还在lambda响应的头中添加了'Access-Control-Allow-Origin'和'Access-Control-Allow-Methods'。我已经尝试了有和没有这些响应的lambda,因为我理解API网关应该解决预检请求。这两种方式都返回CORS 204错误。
const dynamo = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event, context) => {
let body;
let statusCode = 200;
const headers = {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS,PUT,GET'
};
try {
switch (event.routeKey) {
case "GET /items":
// database call
case "PUT /items":
// databse put
default:
throw new Error(`Unsupported route: "${event.routeKey}"`);
}
} catch (err) {
statusCode = 400;
body = err.message;
} finally {
body = JSON.stringify(body);
}
return {
statusCode,
body,
headers
};
};
我相信我应该在Postman中看到我的头,但我没有。我知道API网关正在更新,因为如果我在API网关控制台中删除Access-Control-Allow-Origin,我的GET请求也会因CORS而失败。
1条答案
按热度按时间nfs0ujit1#
我在这里找到了解决方案:aws apigateway未返回预期的预检标头,CORS
解决方案是不使用CORS的API网关,因为它根本不起作用。我不得不添加一个OPTIONS路由并返回所需的头。
沮丧since AWS docs说以下。
If you configure CORS for an API, API Gateway automatically sends a response to preflight OPTIONS requests, even if there isn't an OPTIONS route configured for your API. For a CORS request, API Gateway adds the configured CORS headers to the response from an integration.