带有 AWS cognito 的无服务器框架生成 CORS 错误
问题描述
我从 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 尝试使用令牌,那么它也不起作用(但在开发中工作正常).我什至不再相信这是一个 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!
相关文章