Fail to enable CORS for API Gateway functions

18,237

Solution 1

Firstly please select your root resource and select "Enable CORS". It will enable CORS to all methods. Ideally it should work. If in case it doesn't work Please add an empty json in the response as I have marked in the screenshot attached. I believe you don't have any default response header added in your OPTIONS method response (in Method Response ). Please refer screenshot

enter image description here

Solution 2

Create a new model from the left menu that you will call Empty and it works

empty model

Solution 3

I had a CORS problem with API Gateway + Lambda and the above answers did not help me but I figured out I needed to add some headers information to my response code in my API.

I needed to add the res.statusCodeand the two headers.

// GET
// get all myModel
app.get('/models/', (req, res) => {
  const query = 'SELECT * FROM MyTable'
  pool.query(query, (err, results, fields) => {
    //...

    const models = [...results]
    const response = {
      data: models,
      message: 'All models successfully retrieved.',
    }
    //****** needed to add the next 3 lines
    res.statusCode = 200;
    res.setHeader('content-type', 'application/json');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.send(response)
  })
})
Share:
18,237
Jiew Meng
Author by

Jiew Meng

Web Developer & Computer Science Student Tools of Trade: PHP, Symfony MVC, Doctrine ORM, HTML, CSS, jQuery/JS Looking at Python/Google App Engine, C#/WPF/Entity Framework I hope to develop usable web applications like Wunderlist, SpringPad in the future

Updated on June 22, 2022

Comments

  • Jiew Meng
    Jiew Meng almost 2 years

    I get

    enter image description here

    While attempting to enable CORS on API Gateway, why is that and how do I resolve this? These functions are deployed using AWS SAM. But I notice if I create my own APIs via AWS Console this happens too

    The errors looks like:

    • invalid model name specified application/json=Empty
    • invalid response status code specified

    I found I seem to need to add an "Empty" response model myself?


    Now, I get

    Add Access-Control-Allow-Origin Integration Response Header Mapping to POST method (invalid response status code specified)

    How do I resolve this?