【问题标题】:PHP Vs JQuery Web api2PHP 与 JQuery Web api2
【发布时间】:2015-07-10 20:12:54
【问题描述】:

好吧,这里的标题真的很糟糕,但我没有其他方法可以解释我的服务器发生了什么。

我有一个普通的 web api2,新的。我安装了跨域,只放了

config.EnableCors();在webapiconfig

我有一个包含此方法的 MailController:

 [HttpPost]//omUrl/{url?}
        [Route(@"~/api/Mail/MailOpen")]
        public void MailOpen()
        {
            try
            {
                File.Create(@"D:\Emails\Alive.html");

            }
            catch (Exception ex)
            {
                // ignored
            }
        }

并使用此主机在网络上运行:http://localhost:56212/

所以,我正在尝试发布一些数据以检查跨域策略,并使用此 php 代码发布:

<?php 
$url = 'http://localhost:56212/api/Mail/MailOpen';
$data = array('Smtp' => 'value1', 'Subject' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);
 ?>

此代码到达服务器并创建 Alive.html,等等。我怎么会问自己,我在这个控制器上还没有任何跨域策略?..

所以我尝试运行这段 javascript 代码:

<script>

 $.get(
     "http://localhost:56212/api/Mail/MailOpen",
     { 'G': "aa94a7cf-7794-41ff-b8d0-fcfe34fcb19c" }, // put your parameters here
     function (responseText) {
           console.log(responseText);

     }

    );
</script>

假设做同样的事情..但我得到这个错误:

jquery-1.11.2.min.js:4 GEThttp://localhost:56212/api/Mail/MailOpen?G=aa94a7cf-7794-41ff-b8d0-fcfe34fcb19cm.ajaxTransport.send@jquery-1.11.2.min.js:4m.extend.ajax@jquery-1.11.2.min.js: 4m.each.m.(匿名函数)@jquery-1.11.2.min.js:4m.extend.getJSON@jquery-1.11.2.min.js:4(匿名函数)@index.html:6 index.html:1 XMLHttpRequest 无法加载 http://localhost:56212/api/Mail/MailOpen?G=aa94a7cf-7794-41ff-b8d0-fcfe34fcb19c。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'null' 不允许访问。响应的 HTTP 状态代码为 405。

这很正常,因为我还没有任何政策。

谁能告诉我为什么 php 工作并且 jQuery 返回错误?

所有。]

编辑:

这更糟糕.. 我刚刚看到我正在尝试使用GET 发布。

所以我将我的请求更改为发布,服务器接受了它并且它工作了,它甚至创建了文件,但是给我一个错误index.html:1 XMLHttpRequest cannot load http://localhost:56212/api/Mail/MailOpen. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

它如何给出错误并且仍然有效?

更好的是,这是怎么回事!?

【问题讨论】:

    标签: php security web asp.net-web-api cross-domain


    【解决方案1】:

    CORS 是一种特定于浏览器的安全机制。您的 PHP 不是典型的 Web 浏览器,不需要强制执行 CORS 策略。

    来自维基百科:

    CORS 标准描述了新的 HTTP 标头,它为浏览器和服务器提供了一种仅在获得许可时才请求远程 URL 的方法。尽管服务器可以执行一些验证和授权,但通常浏览器有责任支持这些标头并尊重它们施加的限制。 对于可以修改数据的 AJAX 和 HTTP 请求方法(通常是 GET 以外的 HTTP 方法,或用于某些 MIME 类型的 POST),规范要求浏览器“预检”请求,通过 HTTP OPTIONS 请求从服务器请求支持的方法标头,然后,在服务器“批准”后,使用实际的 HTTP 请求方法发送实际请求。服务器还可以通知客户端是否应该将“凭据”(包括 Cookie 和 HTTP 身份验证数据)与请求一起发送。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 2023-03-31
      • 2023-03-14
      相关资源
      最近更新 更多