在我的本地开发人员计算机上,我在WAMP中运行服务器端PHP代码,在AngularJS中编写客户端代码。在我的开发者机器上,这很好用。当我尝试在我的Android手机上测试代码时,http get请求失败。当我直接点击服务时它工作正常,但是当从AngularJS调用它时,它返回0错误代码。
我认为这是一个CORS问题,但其他解决方案似乎对我不起作用。
PHP代码:
// Allow CORS
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
}
角度代码:
$scope.getStuff = function(){
$http.get("http://localhost/appname/index.php/GetStuff/" + id, {
headers: { 'Content-Type': 'application/json; charset=utf-8' }
})
.success(function (response) {
// do stuff
});
}
// Htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin"
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"
在httpd.conf
<Directory "c:/wamp/www/">
Options Indexes FollowSymLinks
AllowOverride all
Require all granted
</Directory>