在學習 AngularJS 的 $http 服務獲取 JSON 數據時,許多開發者會直接複製 W3CSchool 或菜鳥教程上的示例代碼,但發現完全無法運行。瀏覽器控制台報錯:
已阻止跨源請求:同源策略禁止讀取位於 https://www.runoob.com/try/angularjs/data/Customers_JSON.php 的遠程資源。(原因:CORS 頭缺少 'Access-Control-Allow-Origin')。
這是典型的跨域(CORS)問題。原始代碼嘗試從 runoob.com 獲取數據,但該服務器未設置允許跨域的響應頭。同源策略是瀏覽器的安全機制,禁止腳本跨域訪問資源。
既然目標 API 不支持 CORS,我們可以利用 Yahoo YQL(現已停止服務,但原理通用)作為代理層。YQL 允許跨域請求並返回 JSON 格式數據。
<!DOCTYPE html>
<html>
<body>
<div ng-app="" ng-controller="customersController">
<ul>
<li ng-repeat="x in names"> {{ x.Name + ', ' + x.Country }} </li>
</ul>
</div>
<script>
function customersController($scope, $http) {
$http({
method: 'GET',
url: "https://query.yahooapis.com/v1/public/yql",
params: {
q: 'select * from json where url="https://www.runoob.com/try/angularjs/data/Customers_JSON.php"',
format: "json"
}
}).success(function(response) {
console.log(response);
$scope.names = response.query.results.json.json;
});
}
</script>
<script src="https://apps.bdimg.com/libs/angular.js/1.2.15/angular.min.js"></script>
</body>
</html>
若改用本地 JSON 文件仍無反應,通常是因為:
跨域是前端開發必遇的坑。理解同源策略、掌握代理轉發、配置 CORS 頭是核心技能。學習時勿盲目複製代碼,要看懂網絡請求流程,善用瀏覽器開發者工具分析 Network 和 Console 面板。