php - 访问控制允许来源 angularjs 到 php

标签 php angularjs http cors lighttpd

我的场景由两个网络服务器组成,一个是本地的,一个是远程的。

本地网络服务器 (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/

相关文章:

php - Mysql中的排序机制

AngularJS:错误:$q 未定义

c# - SoapHttpClientProtocol/HttpWebClientProtocol 连接状态

http - net/http.Request.URL.Host 返回空字符串

当数据服务控制台记录数据正常时,Angular2 解析器返回 undefined

javascript - 如何保护来自多个域的 ajax 请求?

php - 如何在使用 exit() 时使用 fetch_assoc while 循环获取所有数据?

php - 使用 WAMP 在本地计算机上创建和使用 Web 服务

javascript - 用 for 循环构建数组

javascript - 如果它是一个多页面应用程序,在 AngularJS 应用程序中创建一个全局 ng-app 范围是否有意义?