访问控制允许Origin angularjs到php


Access-Control-Allow-Origin angularjs to php

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

本地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" => "*" )

要在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基本/摘要身份验证数据,则不能使用通配符作为源。您必须使用实际的源域

setenv.add-response-header = ( "Access-Control-Allow-Origin" => "example.com" )
setenv.add-response-header = ( "Access-Control-Allow-Credentials" => "true" )

因为您正在进行跨域POST,Angular正在进行飞行前OPTIONS请求,以在进行POST之前检查Access Origin标头。浏览器中的NET选项卡将对此进行确认。您的服务器对OPTIONS请求的响应不好,因此Angular拒绝进行POST。

如果您使用POSTMAN将邮件发送到您的服务器,一切正常吗?

我相信可以将Angular配置为不进行飞行前请求。

或者,将服务器配置为正确响应OPTIONS请求,特别是在响应OPTIONS请求时返回正确的Access Origin标头。(OPTIONS只是想知道你的服务器是否设置了这些头,如果没有,为什么还要麻烦进行POST?)

希望这些信息能为你指明正确的方向。

*不能用于凭据。

服务器正在忽略您的setenv.add-response-header语句。

点击此处查看答案:

CORS:当凭证标志为true 时,不能在访问控制允许来源中使用通配符