-1

So am having an issue with CORS and I read through some related questions of folks who also had a CORS problem and tried all of those answers and didn't have any luck; so am now asking my question since none of the other answers did the trick.

I have a website running in GatsbyJS using NodeJS Javascript and an API Gateway with Lambda Proxy Integration. Assume the api endpoint is https://xxxx.execute-api.us-east-1.amazonaws.com/default

JSON:

{
"message": "Welcome"
}

Now the problem is am getting the error that basically says that the 'No Access-Control-Allow-Origin' header is present for same origin. It talks about it missing however I went and followed this guide here and added the options method with Mock https://enable-cors.org/server_awsapigateway.html Re-deployed the api gateway endpoint and even tried adding .set(headers, values) to my superagent get request and still got the same error.

Am out of ideas on how to solve this.

Here's an example of my code:

superagent
  .get('https://xxxx.execute-api.us-east-1.amazonaws.com/default')
  .set('Access-Control-Allow-Origin', '*')
  .set('Access-Control-Allow-Credentials', 'true')
  .set('accept', 'json')
  .end((err, res) => {
    // Calling the end function will send the request
     console.log(res) // I should get welcome back
  });

Lambda:

def lambda_handler(event, context):
    # TODO implement

    website_content = {
        'message': 'welcome'
    }


    return {
        'statusCode': 200,
        'body': json.dumps(website_content)
    }
SixthTitan
  • 17
  • 7
  • What’s the HTTP status code of the response? You can use the Network pane in browser devtools to check. Is it a 4xx or 5xx error rather than a 200 OK success response? – sideshowbarker Apr 07 '20 at 23:30
  • It's a 200 OK success response. – SixthTitan Apr 07 '20 at 23:31
  • Remove the `.set('Access-Control-Allow-Origin', '*') .set('Access-Control-Allow-Credentials', 'true')` from your frontend code. Those are response headers, not request headers. You need to make your API send them as response headers. The lambda code snippet in the question doesn’t show any response headers being added to the response. – sideshowbarker Apr 07 '20 at 23:35
  • Okay so i should add the header before the body in my lambda code? – SixthTitan Apr 07 '20 at 23:37

1 Answers1

0

try the cors npm. for example to Enable All CORS Requests you can use

const cors = require('cors') 
app.use(cors())