I am creating Rest APIs with SAM template.
I am testing these APIs through Postman and everything is working as expected, but as soon I integrate these APIs in my application, I am getting this error:
from origin 'http://localhost:3033' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
This is happening only for PUT, POST and PATCH method. GET method is working fine.
I have added the below in the code return part:
return {
"statusCode": 200,
"headers": {"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "*"},
"body": json.dumps(item)
}
However, the error still shows up.
I created an API and lambda to serve the same function with the console and it was working fine with the Application.
Here is my SAM code for creating an API:
ApiGatewaySignUpFlowUserApi:
Type: AWS::Serverless::Api
Properties:
Name: loadeo_signup
StageName: Stage
Cors: "'*'"
CreateUserSignup:
Type: AWS::Serverless::Function
Properties:
FunctionName: loadeo_create_user_signup
CodeUri: createUserSignup/
Handler: create_user_signup.lambda_handler
Timeout: 5
Runtime: python3.8
Role: arn:aws:iam::272075499248:role/loadeo_lambda_execution
MemorySize: 128
Events:
GetAllUser:
Type: Api
Properties:
Path: /create-user
Method: post
RestApiId:
Ref: ApiGatewaySignUpFlowUserApi
I can't really understand what might be wrong here. Could anyone please help me with this?
Changing the API definition to below helped me solve the issue:
ApiGatewaySignUpFlowUserApi:
Type: AWS::Serverless::Api
Properties:
Name: loadeo_signup
StageName: Stage
Cors:
AllowMethods: "'*'"
AllowHeaders: "'*'"
AllowOrigin: "'*'"
Explicitly specifying the CORS rule helped.