Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

python - Serverless Framework with AWS cognito generates CORS error

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.

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")
     }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Something like this should do it:

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...