KevinY
KevinY

Reputation: 1239

Blocked by CORS policy "...does not have HTTP ok status" (Amplify and ReactJS, AWS Gateway and Lambda)

I'm almost embarassed to be asking this question due to CORS support out there on SO but I can't get by:

Access to XMLHttpRequest at 'https://a93xxxxx.execute-api.eu-west-1.amazonaws.com/dev[object%20Object]' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I've even published my React project with Amplify and attempted it from the real domain name to even eliminate anything to do with the development environment (Cloud 9 running npm version 6.14.8)

I've also made a test running Chrome with the --disable-web-security flag.

My Lambda function contains the following (out of the box stub)

exports.handler = async (event) => {
// TODO implement
const response = {
    statusCode: 200,
//  Uncomment below to enable CORS requests
  headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers" : "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With",
      "Access-Control-Allow-Methods" : "OPTIONS,POST,GET,PUT"
    }

  , 
    body: JSON.stringify("Hello from Lambda!")
};
return response;
};

Note that I've uncommented the CORS request part and the response statusCode is set to 200. The code in my application that execute when a submission form is sent from the client:

    uploadcontactusdata = async data => {
    try {
        console.log("Contact Us pressed")
        const settings = {
            method: 'POST',
            body: JSON.stringify(data),
            
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }
        }

        const fetchResponse = await API.post('econtactus', settings);
        Notification({
            title: 'Success',
            message: 'Notification has been sent',
            type: 'success'
        });
    }
    catch (err) {
        console.log("unable to send");
        console.error(err)
    }
}

I created the API Gateway + Lambda using Amplify (version 4.41.2). Not sure where else to look now. Any clues will be appreciated. Thanks

Upvotes: 1

Views: 1886

Answers (2)

zambono
zambono

Reputation: 1397

When you create a REST Api with Amplify and you have Cognito User Pools and Identity Pool the API is authenticated by iAM role. Your Cognito group has a role which you must find. The new API also created a new policy but they are not linked. Add the policy to the groups you wish to have access to that API. Many answers ask you to create Authorizers and change the authorization type from iAM to the authorizer but that is not what Amplify was intending all along. They want you to control access via iAM roles.

Upvotes: 0

Mickers
Mickers

Reputation: 1449

You can completely get past the need for api gateway by using appsync.

amplify add api

Choose graphql (I have not tried using rest but you shouldn't need it) choose the basic schema, edit it if you'd like, and publish. Once it's published you can create your own method. You can view this inside the AppSync UI under Schema.

type Mutation {
  yourMethod(input: Input!): TableName <-- add your method to the list
}

Now inside Appsync choose Data Sources and add datasource. Give it a name, choose lambda as the type, then find your lambda in the list. Once it's added go back to your schema and find the method you created above. On the right side bar locate your method and click the attach link. Find the data source you just added. Fill out the region and lambda ARN. MAKE SURE you choose new role and not an existing one.

You might need to configure the request and response templates.

For request:

{
  "version" : "2017-02-28",
  "operation": "Invoke",
  "payload": $util.toJson($context.args)
}

For response:

$util.toJson($context.result)

Now you can call your lambda directly from the UI and return your result without worrying about CORS or managing API Gateway.

Upvotes: 0

Related Questions