![](/img/trans.png)
[英]Get data from a API URL in HTML or JSP using Javascript or Ajax
[英]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);
}
});
我在控制台中收到此错误:
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.
我应该怎么做才能避免这个错误? 请帮忙。
您不能发送跨源请求,因为它是一个安全漏洞。
这是因为google.com尚未启用跨源请求。 例如,如果您尝试的网站类似:
$.ajax({
type:"GET",
dataType: 'html',
url: 'https://cors-test.appspot.com/test',
success: function(res){
console.log(res);
}
});
然后您将获得理想的结果
我认为这是由于获取另一个域时的安全问题。 请检查一下
“所请求的资源上没有'Access-Control-Allow-Origin'标头”
如果您控制后端,则可以将此请求代理到后端,即使用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将能够获取数据,因为它不检查CORS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.