因为在AngularJS中使用CORS和http身份验证可能很棘手,所以我编辑了问题以分享一个经验教训。首先,我要感谢igorzg。他的回答对我很有帮助。场景如下:您想使用AngularJS $ http服务将POST请求发送到另一个域。获取AngularJS和服务器设置时,需要注意一些棘手的事情。
首先:在您的应用程序配置中,您必须允许跨域调用
/**
* Cors usage example.
* @author Georgi Naumov
* gonaumov@gmail.com for contacts and
* suggestions.
**/
app.config(function($httpProvider) {
//Enable cross domain calls
$httpProvider.defaults.useXDomain = true;
});
第二:您必须指定withCredentials:true,并在请求中输入用户名和密码。
/**
* Cors usage example.
* @author Georgi Naumov
* gonaumov@gmail.com for contacts and
* suggestions.
**/
$http({
url: 'url of remote service',
method: "POST",
data: JSON.stringify(requestData),
withCredentials: true,
headers: {
'Authorization': 'Basic bashe64usename:password'
}
});
答案:服务器设置。您必须提供:
/**
* Cors usage example.
* @author Georgi Naumov
* gonaumov@gmail.com for contacts and
* suggestions.
**/
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://url.com:8080");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
对于每个请求。收到OPTION时,您必须通过:
/**
* Cors usage example.
* @author Georgi Naumov
* gonaumov@gmail.com for contacts and
* suggestions.
**/
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header( "HTTP/1.1 200 OK" );
exit();
}
HTTP身份验证以及之后的所有其他操作。
这是在PHP中使用服务器端的完整示例。
<?php
/**
* Cors usage example.
* @author Georgi Naumov
* gonaumov@gmail.com for contacts and
* suggestions.
**/
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://url:8080");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header( "HTTP/1.1 200 OK" );
exit();
}
$realm = 'Restricted area';
$password = 'somepassword';
$users = array('someusername' => $password);
if (isset($_SERVER['PHP_AUTH_USER']) == false || isset($_SERVER['PHP_AUTH_PW']) == false) {
header('WWW-Authenticate: Basic realm="My Realm"');
die('Not authorised');
}
if (isset($users[$_SERVER['PHP_AUTH_USER']]) && $users[$_SERVER['PHP_AUTH_USER']] == $password)
{
header( "HTTP/1.1 200 OK" );
echo 'You are logged in!' ;
exit();
}
?>
我的博客上有一篇有关此问题的文章,可以在这里看到。