因为在AngularJS中使用CORS和HTTP身份验证可能会有些棘手,所以我编辑了问题,分享了一个学到的教训。首先,我要感谢igorzg。他的答案帮了我很多。情境如下:您想使用AngularJS $http服务向不同的域发送POST请求。当使用AngularJS和服务器设置时,有几个需要注意的棘手问题。
第一点: 在应用程序配置中,必须允许跨域调用。
第二步: 您必须将withCredentials设置为true,并将用户名和密码放入请求中。
第一点: 在应用程序配置中,必须允许跨域调用。
/**
* 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();
}
?>
我的博客上有一篇关于这个问题的文章,可以在 这里 查看。