通过SAM创建API时,在飞行前响应中Access-Control-Allow-Headers不允许请求标头字段的内容类型 [英] Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response when creating API through SAM
问题描述
我正在使用SAM模板创建Rest API.
I am creating Rest APIs with SAM template.
我正在通过Postman测试这些API,并且一切都按预期工作,但是一旦将这些API集成到我的应用程序中,就会出现此错误:
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.
这仅在PUT,POST和PATCH方法中发生.GET方法工作正常.
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)
}
但是,错误仍然出现.
我创建了一个API和lambda来与控制台提供相同的功能,并且可以与Application正常工作.
I created an API and lambda to serve the same function with the console and it was working fine with the Application.
这是我用于创建API的SAM代码:
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?
推荐答案
将API定义更改为以下内容可以帮助我解决该问题:
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: "'*'"
明确指定CORS规则有帮助.
Explicitly specifying the CORS rule helped.
这篇关于通过SAM创建API时,在飞行前响应中Access-Control-Allow-Headers不允许请求标头字段的内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!