0

I performed a GET request via Postman successfully, but it is failing in the browser due to CORs

I've tried both XHR and Jquery Ajax (see codepen here), and I've also set Access-Control-Allow-Origin

XHR

var data = "{\"value\":'174.9',\"time_stamp\":\"2019-10-01T18:56:45-04:00\",\"date\":\"2019-10-01\",\"name\":'weight',\"category\":'weight'}";

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://f17c15m5a79.execute-api.us-east-2.amazonaws.com/production/quantified-self-metrics");

xhr.send(data);

Jquery Ajax

  var settings = {
    async: true,
    crossDomain: true,
    url:
      "https://f17c15m5a79.execute-api.us-east-2.amazonaws.com/production/quantified-self-metrics",
    method: "GET",
    headers: {
      "Access-Control-Allow-Origin": "*"
    },
    data:
      '{"value":\'175.9\',"time_stamp":"2019-10-02T18:56:45-04:00","date":"2019-10-02","name":\'weight\',"category":\'weight\'}'
  };

$.ajax(settings).done(function (response) {
  console.log(response);
});

The response I receive from the browser is the following:

Access to XMLHttpRequest at 'https://f17c15m5a79.execute-api.us-east-2.amazonaws.com/production/quantified-self-metrics?{%22value%22:%27175.9%27,%22time_stamp%22:%222019-10-02T18:56:45-04:00%22,%22date%22:%222019-10-02%22,%22name%22:%27weight%27,%22category%22:%27weight%27}' from origin 'https://codepen.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've also implemented the solution found in this question

Chris
  • 5,444
  • 16
  • 63
  • 119
  • As the error message states the response you receive from API Gateway doesn't include necessary CORS headers. You probably didn't set it up correctly on API Gateway/AWS Lambda side. How does your setup look like on AWS side? – Dunedan Oct 05 '19 at 21:12

1 Answers1

-1

You need to prepend https://cors-anywhere.herokuapp.com/ to your request url. So it will look like https://cors-anywhere.herokuapp.com/https://f17c15m5a7.execute-api.us-east-2.amazonaws.com/production/quantified-self-metrics

Niko Modric
  • 635
  • 4
  • 13