javascriptsecurityconstruct-2

Javascript $.GET - Access-Control-Allow-Origin ERROR


I try to collect the html text from different sites and after that to search if those sites contain my pub-id. The problem is that I can't acces other websites, becase of Access-Control-Allow-Origin.

Failed to load http://example.com/: Redirect from 'http://example.com/' to 'http://example.com/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50000' is therefore not allowed access.

Here you can take a look at my code:

var site = 'http://example.com';
var pub_id = 'pub-27638960xxxxxx';
var found = -1;

$.get(site, function(data, status){
        alert('Data: ' + data + '\nStatus: ' + status);
        found = data.indexOf(pub_id);
 if(found >=0)
 {
         alert('Found at position: ' + found);
 }
    });

This code is add in my Construct 2 project. What is more interesting is that if I will run/preview my game in NW.js, the code will work. If I will preview/run in Chrome, Firefox, Edge, etc, the code will NOT work.

Somebody knows how to solve this? I understand that I need to make a request to that server, but I don't know how.

Thank you!

PS: If you know other way to make this in Javascript or Construct 2, I'm all ears.


Solution

  • The requesting server has to SET the 'Access-Control-Allow-Origin' to your origin domain:

    in php header('Access-Control-Allow-Origin: http://localhost:500');