0
var $ = require('jquery');

$.ajax({
  type:"GET",
  dataType: 'html',
  url: 'http://www.google.com/',
  success: function(res){
    console.log(res);
  }
});

I am getting this error in the console:

XMLHttpRequest cannot load http://www.google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

What can I do to avoid this error? Please help.

remelkabir
  • 366
  • 1
  • 4
  • 11

4 Answers4

1

You cannot send cross origin requests because it is a security vulnerability.

JakeBoggs
  • 274
  • 4
  • 17
1

If you control the backend, you can proxy this request to the backend, i.e. using PHP:

// get.php
echo file_get_contents($_GET['url']);

// frontend JS
$.ajax({
  type:"GET",
  dataType: 'html',
  url: '/get.php?url=http://www.google.com/',
  success: function(res){
    console.log(res);
  }
});

PHP will be able to fetch the data, as it's not checking CORS.

Andrey E
  • 605
  • 4
  • 8
0

Its because google.com goes not have cross origin requests enabled. If you try a site that does like for example:

$.ajax({
  type:"GET",
  dataType: 'html',
  url: 'https://cors-test.appspot.com/test',
  success: function(res){
    console.log(res);
  }
});

Then you will get the desired result

red house 87
  • 1,837
  • 9
  • 50
  • 99
0

I think this is because of security problem while fetching another domain. Please check this
"No 'Access-Control-Allow-Origin' header is present on the requested resource"

saifudeen ni
  • 145
  • 9