【发布时间】:2014-11-09 14:53:23
【问题描述】:
我正在将 AngualrJS 用于带有一些 PHP 的单页应用程序(MAMP PRO 作为开发环境。)
在 angular http get 请求中,我有 3rd 方 api 提供程序,它在 http 请求中返回 json。
当我提出请求时,我得到“请求的资源上没有 'Access-Control-Allow-Origin' 标头”。
基本上我现在被困在 CORS 中超过 8 小时!不知道如何让浏览器 (Chrome/FF) 覆盖 CORS 并发送 http 请求。
这里是 Controller.js 中的获取请求:
在 Angular js 中:
factory.fetchJson = function (filePath) {
return $http.get(filePath)
.success(function (data, status) {
return data;
console.log('Success Fetch JSON', status);
}).error(function (data, status, headers, config) {
console.log('Error Fetch JSON', status);
});
}
在 angualrjs Controller.js 中设置为允许 CORS
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
}
]);
在 index.php 标头中允许 CORS 的设置:
<html>
<?php
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
echo "You have CORS!";
?>
我不追求 JSOP 或 MIM 代理。
救命!
【问题讨论】:
标签: javascript php angularjs xmlhttprequest cors