我的场景由两个webserver组成,一个是本地的,一个是远程的.
本地Web服务器(Apache)处理一个Web应用程序,我想在其中向远程Web服务器(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标头
<?php header("Access-Control-Allow-Origin: *"); ?>
我还想补充一点,如果您要发送http basic / digest auth数据,则不能使用通配符作为原点.您必须使用实际的源域
setenv.add-response-header = ( "Access-Control-Allow-Origin" => "example.com" ) setenv.add-response-header = ( "Access-Control-Allow-Credentials" => "true" )