0

I am trying to make an ajax request using window.fetch() to an AWS lambda function of mine.

I followed the AWS Lambda guide on setting up CORS (and redeployed).

I followed the MDN documentation on adding headers to window.fetch() to pass in my API key.

My code looks like this:

   let myHeaders = new Headers();
   myHeaders.append('x-api-key', lambda_key);
   fetch('https://comically_long_aws_url.com/blah', {
        headers: myHeaders,
    })
    .then((res)=>{
        console.log('success,', res)
    })
    .catch((err)=>{
        console.log('err', err);
    });

If I look at the network tab, I see that both the OPTIONS and GET request were successful. Indeed, the GET returned the expected information:

Successful OPTIONS request:

Network tab for OPTIONS request

Successful GET request:

Network tab for GET request

Expected data in GET request response body:

Preview of response.body

Unexpected errors displaying in console:

enter image description here

Why is the window.fetch().catch() error handler being invoked? Why is there a console error when the network call appears to be successful?

Caleb Jay
  • 2,159
  • 3
  • 32
  • 66
  • 3
    The CORS headers are in the OPTIONS response but not in the GET. Must be in both – charlietfl Nov 12 '18 at 03:39
  • But why is the data still getting returned? – Caleb Jay Nov 12 '18 at 03:57
  • Do you mean the client GET headers? So i should add type:cors to the fetch? – Caleb Jay Nov 12 '18 at 03:58
  • 3
    Because server sends it. But browser won't let you access it when headers are missing. It's not server's responsibility to not send the data. CORS is approved/dissaproved by the browser – charlietfl Nov 12 '18 at 03:59
  • 2
    As for the headers ...server needs to add the access-control headers to response. Can't do it client side. The most critical one is `access-control-allow-origin` – charlietfl Nov 12 '18 at 04:02
  • That was the issue, plus also ensuring that I put the CORS header in the response of the Lambda function - https://stackoverflow.com/a/47044446/2590119 Would you like to add your comments as an answer so you can get credit and I can "close" this question? – Caleb Jay Nov 13 '18 at 20:57

0 Answers0