简体   繁体   中英

Get html file from a given url using javascript($ajax)

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.

您不能发送跨源请求,因为它是一个安全漏洞。

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

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"

If you control the backend, you can proxy this request to the backend, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM