带有AWS Cognito的无服务器框架会产生CORS错误 [英] Serverless Framework with AWS cognito generates CORS error
问题描述
我从Angular前端收到此错误消息,但无权触摸我的lambda代码:
I get this error message from the Angular frontend and I am not authorized to touch my lambda code:
`Access to fetch at 'https://testapicd.***.***.com/localization/v1/role' from origin 'https://localization.test.***.***.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.`
我到处都看过了,我的代码似乎没有错误。我的无服务器代码是
I have looked everywhere and there seems to be no bug in my code. My serverless code is
getrole:
handler: v1/handler_get_role.get_role
name: get_role
events:
- http:
path: v1/role
method: get
cors: true
authorizer:
name: CognitoCSAuthorizer
type: COGNITO_USER_POOLS
arn: ${file(config.${self:provider.stage}.json):userpoolarn}
我已经对所有设置进行了三遍检查,一切似乎都正确。有什么建议怎么办?该功能在开发环境中有效,但当我将其部署到测试环境中时则无效。
I have triple-checked all the settings and everything seems correct. Any advice what to do? The functionality works in the dev environment but not when I deploy it to the test environment.
如果我直接针对API尝试使用令牌,那么它也不起作用(但在dev中工作正常)。我什至不再相信这是CORS问题。我认为jwt令牌是错误的。
If I try the token directly against the API, then it does not work either (but worked fine in dev). I don't even believe anymore that it is a CORS problem. I think that the jwt token is wrong.
def get_role(event, context):
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*', # Required for CORS support to work
'Access-Control-Allow-Credentials': 'true',
},
'body': json.dumps("TEST")
}
推荐答案
我已经为这个问题挣扎了好几个小时(如果不是几天的话)不仅如此,事实证明,我不仅不得不在 serverless.yml
文件上启用cors,而且还要将响应标头作为属性添加到从您返回的对象中Lambda。
I have wrestled with this problem for hours (if not days) before and it turned out not only I had to enable cors on the serverless.yml
file but also add the response headers as attributes in the object you return from your Lambda.
应该执行以下操作:
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
product: product
}),
};
此文章挽救了我的生命,希望它能拯救您的生命!
This article saved my life back then and I hope it saves yours!
这篇关于带有AWS Cognito的无服务器框架会产生CORS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!