Access-Control-Allow-Origin angularjs到php

我的场景由两个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" )

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...