Why is this AWS Amplify API blocked by CORS policy

This REST API in AWS Amplify is created with the commands found below. Without changing any code in the generated Express function, the post request found below results in the following error:

Access to XMLHttpRequest at 'https://example-id.execute-api.ca-central-1.amazonaws.com/dev/example-path' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The Express function by default contains code to avoid CORS issues under the comment Enable CORS for all methods at line 21. What can be done to allow requests to be passed into the API function?

Default Express code in app.js (backend)

// Enable CORS for all methods
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
});

// Example POST method
app.post('/create-customer', function(req, res) {
  // Add your code here
  res.json({success: 'post call succeed!', url: req.url, body: req.body})
});

Amplify commands

amplify add api

? Please select from one of the below mentioned services: REST
? Provide a friendly name for your resource to be used as a label for this category in the project: example
? Provide a path (e.g., /book/{isbn}): /example-path
? Choose a Lambda source Create a new Lambda function
? Provide a friendly name for your resource to be used as a label for this category in the project: example
? Provide the AWS Lambda function name: example
? Choose the runtime that you want to use: NodeJS
? Choose the function template that you want to use: Serverless ExpressJS function (Integration with API Gateway)
? Do you want to access other resources in this project from your Lambda function? No
? Do you want to invoke this function on a recurring schedule? No 
? Do you want to configure Lambda layers for this function? No
? Do you want to edit the local lambda function now? No

? Restrict API access Yes
? Who should have access? Authenticated users only
? What kind of access do you want for Authenticated users? create, update, delete
? Do you want to add another path? No

amplify push

Component.js

const apiName = 'example';
const path = '/example-path';
const myInit = {
    body: JSON.stringify({
        example: example,
    })
};

API
.post(apiName, path, myInit)
.then(response => {
    console.log(response);
})
.catch(error => {
    console.log(error.response);
});

Source: Ask Javascript Questions

One Reply to “Why is this AWS Amplify API blocked by CORS policy”

LEAVE A COMMENT