camdev
camdev

Reputation: 231

No 'Access-Control-Allow-Origin' header is present on the requested resource

I am having a beginner trouble about No 'Access-Control-Allow-Origin' header is present on the requested resource. My solution here is by removing the s on the https and it works but I think that not the real solution here.

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
        <script>
        function arrayToTable(tableData) {
                var table = $('<table></table>');
                $(tableData).each(function (i, rowData) {
                    var row = $('<tr></tr>');
                    $(rowData).each(function (j, cellData) {
                        row.append($('<td>'+cellData+'</td>'));
                    });
                    table.append(row);
                });
                return table;
            }

            $.ajax({
                type: "GET",
                url: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/162656/csv_data.csv",
                success: function (data) {
                    $('.here').append(arrayToTable(Papa.parse(data).data));
                }
            });
        </script>

Upvotes: 2

Views: 7529

Answers (1)

Maria Ines Parnisari
Maria Ines Parnisari

Reputation: 17466

Your AJAX call needs to send a preflight request first to get "permission" to do this request. You can trigger this by adding the Content-Type header to the request with a value other than application/x-www-form-urlencoded, multipart/form-data, or text/plain.

$.ajax({
  type: "GET",
  contentType: 'html',
  url: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/162656/csv_data.csv",
  success: function(data) {
    $('.here').append(data);
  }
});

The code above will issue two requests: an OPTIONS request and a GET request. I suggest that you run the demo here (https://jsfiddle.net/bjyzs8y1/) and analyze the network tab to see the requests and responses. enter image description here

Upvotes: 1

Related Questions