加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Access-Control-Allow-Origin angularjs到php

发布时间:2020-12-17 07:14:20 所属栏目:安全 来源:网络整理
导读:我的场景由两个webserver组成,一个是本地的,一个是远程的. 本地Web服务器(Apache)处理一个Web应用程序,我想在其中向远程Web服务器(Lighttpd)发出ajax请求. Ajax请求使用angularjs $http. var req = { method: 'POST',url: 'http://url/myphp.php',headers: {
我的场景由两个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" )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读