1. Create a Lambda function: called `get-groups`

const data = [
    {name: 'angular', id: 1},
    {name: 'react', id: 2},
    {name: 'vue', id: 3}
];

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({items: data}),
    };
    return response;
};

To prevent CORS problems, we enables CORS headers as well.

 

2. Create an API Gateway

  • For REST API
  • Build a New Rest API
  • Actions -> Create Resource, this is used as endpoint, let's named `groups`
  • Action -> Create Method, `GET`

[AWS] Lab: Create a REST API with API Gateway and Lambda with CORS

  • Action -> Deploy

[AWS] Lab: Create a REST API with API Gateway and Lambda with CORS

 

3. After deployed, it generate a URL you can used for testing in POSTMAN

GET: https://<id>.execute-api.us-east-1.amazonaws.com/dev/groups

 

4. Using the same approach to create a POST method. But this time, even we enabled CORS in the code, after deploy, we will still get CORS error. 

This is because we need to enable CORS for OPTIONS as well.

  • Actions -> Enable CORS
  • [AWS] Lab: Create a REST API with API Gateway and Lambda with CORS
  • Deploy API
  • You should see OPTIONS has been enabled
  • [AWS] Lab: Create a REST API with API Gateway and Lambda with CORS

相关文章:

  • 2021-11-29
  • 2021-10-01
  • 2022-12-23
  • 2022-12-23
  • 2021-05-20
  • 2021-09-13
  • 2022-12-23
  • 2021-10-07
猜你喜欢
  • 2022-12-23
  • 2022-02-16
  • 2021-11-02
  • 2021-11-02
  • 2022-01-07
  • 2021-11-18
  • 2021-07-08
相关资源
相似解决方案