我从 Angular 前端收到这条错误消息,我无权修改我的 lambda 代码:
`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.`
我到处都看了,我的代码中似乎没有错误。我的无服务器代码是
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}
我已经对所有设置进行了三重检查,一切似乎都是正确的。有什么建议怎么办?该功能在开发环境中有效,但在我将其部署到测试环境时却无效。
如果我直接针对 API 尝试 token ,那么它也不起作用(但在开发中运行良好)。我什至不再相信这是一个 CORS 问题。我认为 jwt token 是错误的。
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,而且还要将响应 header 作为属性添加到您从 Lambda 返回的对象。
应该这样做:
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
product: product
}),
};
这article当时救了我的命,我希望它能救你的命!
关于python - 带有 AWS cognito 的无服务器框架生成 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54805730/