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.

4
  • You can use YQL Commented Jul 29, 2017 at 16:59
  • try with ` crossDomain: true` Commented Jul 29, 2017 at 17:06
  • crossDomain:true didn't work. Commented Jul 29, 2017 at 17:12
  • @ArunpandianM that is not what crossDomain:true is even for. Read the $.ajax docs Commented Jul 29, 2017 at 17:28

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.