如何清除此错误
已被CORS策略阻止:所请求的资源上没有'Access-Control-Allow-Origin'标头
同时通过jQuery调用google API距离矩阵
使用此来源
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=[API_KEY]", function(data, status){
console.log("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
这是跨源问题。出于安全原因,浏览器会阻止来自其他域的请求。您必须在http请求中添加“ Access-Control-Allow-Origin”标头,以指定您的域可以访问您所点击的api。
您可以参考这个问题jQuery ajax request being block because Cross-Origin
当您尝试从您的域(甚至是本地主机)访问另一个域上的API /资源时,会发生此错误。
有一些技巧可以消除此错误,如下所示。
1)尝试将其添加到您的AJAX通话中>
crossDomain: true dataType: 'jsonp'
例如
$.ajax({ type: 'GET', crossDomain: true, dataType: 'jsonp', url: 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=[API_KEY]', success: function(jsondata){ # Your logic here } })
2)如果仍然不起作用,请尝试运行此命令chrome.exe --user-data-dir =“ C:/ Chrome开发者会话” --disable-web-security
这将打开Google Chrome,在其中不会出现任何跨域错误注意-仅适用于测试,不适用于生产。
3)向要使用的API /资源的供应商注册。它们将为您提供某种Authentication Key
类型,在API调用中使用该类型时,将为您提供所需的响应。我建议您阅读以下文章,这可能会对您有所帮助。Loading cross-domain endpoint with jQuery AJAX
Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource