Fail to enable CORS for API Gateway functions

旧街凉风 提交于 2019-12-03 10:56:18

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

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

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)
  })
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!