COR 阻止 PUT 方法的 AWS Preflight 响应
Posted
技术标签:
【中文标题】COR 阻止 PUT 方法的 AWS Preflight 响应【英文标题】:AWS Preflight response blocked by CORs for PUT method 【发布时间】:2021-06-20 01:41:05 【问题描述】:这是实际的错误
Access to XMLHttpRequest at 'https://uzk3crusd9.execute-api.us-east-2.amazonaws.com/production/contact' from origin 'https://seb-contact-form.netlify.app' has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
在本地运行正常,但是当我连接到Netlify时出现了这个错误。
我的 lambda 函数:
const AWS = require('aws-sdk');
AWS.config.update(
region: 'us-east-2'
);
const dynamodb = new AWS.DynamoDB.DocumentClient();
const dynamodbTableName = 'contact-form';
const contactPath = '/contact';
exports.handler = async function(event)
console.log('Request event: ', event);
let response;
switch(true)
case event.httpMethod === 'POST' && event.path === contactPath:
response = await createContact(JSON.parse(event.body));
break;
default:
response = buildResponse(404, '404 Not Found');
return response;
async function createContact(requestBody)
const params =
TableName: dynamodbTableName,
Item: requestBody
return await dynamodb.put(params).promise().then(() =>
const body =
Operation: 'SAVE',
Message: 'SUCCESS',
Item: requestBody
return buildResponse(200, body);
, (error) =>
console.error('Oh no! Something went wrong...', error);
)
function buildResponse(statusCode, body)
const response =
statusCode,
headers:
'Content-Type': 'application/json',
"Access-Control-Allow-Headers" : "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
"Access-Control-Allow-Methods" : "OPTIONS,POST,PUT,PATCH",
"Access-Control-Allow-Credentials" : true,
"Access-Control-Allow-Origin" : "*",
"X-Requested-With" : "*"
,
body: JSON.stringify(body)
return response;
我意识到这里使用 post 和 put 方法之间存在混合。但它在本地和一些 youtube 教程中运行良好。
【问题讨论】:
【参考方案1】:有两个步骤:
-
在您的 Lambda 中启用对 CORS 的支持(您已经这样做了)。
在 API Gateway 端点本身中启用 CORS 支持(我相信您没有这样做)。
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.html
【讨论】:
好建议,但我已经在 POST 和 OPTIONS 方法上启用了 CORS。以上是关于COR 阻止 PUT 方法的 AWS Preflight 响应的主要内容,如果未能解决你的问题,请参考以下文章
aws 的 s3 put_object vs upload_file
如何在 put() 期间阻止 ConcurrentHashMap get() 操作