My locally hosted React application calls this AWS Serverless API Gateway built on CloudFormation Stack using Infrastructure Composer endpoint but encounters a CORS error. Although I have configured the Cors settings in my SAM template to allow all origins ('*'), the issue persists.
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);
}
};
SAM
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
Without seeing the code you've used to handle the function it's difficult to identify the issue. But you need to make sure the lambda response for the GET request matches the headers in the OPTIONS Cors response.