我的场景由两个网络服务器组成,一个是本地的,一个是远程的。
本地网络服务器 (Apache) 处理一个网络应用程序,我想在其中向远程网络服务器 (Lighttpd) 发出 ajax 请求。
Ajax 请求使用 angularjs $http。
var req = {
method: 'POST',
url: 'http://url/myphp.php',
headers: {
'Authorization': 'Basic ' + btoa('username:password'),
'Content-Type': 'application/x-www-form-urlencoded'
},
xhrFields: {
withCredentials: true
},
crossDomain: true,
data: xmlString
}
$http(req).then(function () {
console.log("OK!");
});
远程 php 脚本是:
<?php
echo "You have CORS!";
?>
不幸的是我得到了一个
401 Unhauthorized
XMLHttpRequest cannot load http://url/myphp.php. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access. The response had HTTP status code 401.
远程 Web 服务器启用了 .htpasswd 身份验证模式并配置了 CORS 请求。
按照一段lighttpd.conf
setenv.add-response-header = ( "Access-Control-Allow-Origin" => "*" )
最佳答案
要使 add-response-header 在 lighttpd 中工作,您必须在 server.modules 中启用 mod_setenv。但是,您必须在 mod_status 之前启用此 mod_setenv。
server.modules = (
# ...
"mod_fastcgi",
"mod_rewrite",
"mod_redirect",
"mod_setenv", ## before mod_status
"mod_status",
# ...
)
或者,您可以使用 PHP 输出 cors header
<?php
header("Access-Control-Allow-Origin: *");
?>
我还想补充一点,如果您要发送 http basic/digest 身份验证数据,则不能对来源使用通配符。您必须使用实际的源域
setenv.add-response-header = ( "Access-Control-Allow-Origin" => "example.com" )
setenv.add-response-header = ( "Access-Control-Allow-Credentials" => "true" )
关于php - 访问控制允许来源 angularjs 到 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34412418/