我的本地托管 React 应用程序使用基础设施 Composer 端点调用基于 CloudFormation Stack 构建的 AWS 无服务器 API 网关,但遇到 CORS 错误。尽管我已在 SAM 模板中配置 Cors 设置以允许所有来源(“*”),但问题仍然存在。
const fetchUser = async (userId) => {
try {
const response = await fetch(`https://<api-id>.execute-api.<region>.amazonaws.com/Prod/user/${userId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
// Include additional headers if required
}
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
};
萨姆
Transform: AWS::Serverless-2016-10-31
Resources:
UserApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
DefinitionBody:
openapi: '3.0'
paths:
/user/{userId}:
get:
x-amazon-apigateway-integration:
httpMethod: GET
type: aws_proxy
uri: !Sub arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${DemoUserMgmt.Arn}/invocations
responses: {}
Cors:
AllowMethods: "'GET,POST,OPTIONS'"
AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'"
AllowOrigin: "'*'" # Adjust origin as needed
DemoUserMgmt:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/function/user/UserManagement
Handler: handler.handler
Runtime: python3.12
Events:
UserApiGETuseruserId:
Type: Api
Properties:
Path: /user/{userId}
Method: GET
RestApiId: !Ref UserApi
如果没有看到用于处理该函数的代码,就很难识别问题。但您需要确保 GET 请求的 lambda 响应与 OPTIONS Cors 响应中的标头匹配。