【问题标题】:How to fix CORS Error fix Angular and PHP如何修复 CORS 错误修复 Angular 和 PHP
【发布时间】:2021-11-30 21:01:47
【问题描述】:

我正在尝试通过构建一个解决方案来学习 Angular,该解决方案与在 PHP 上作为 API 运行的 IIS 服务器进行通信。

IIS 使用 Windows 身份验证运行以识别用户。 IIS/PHP 组合有效。

PHP:

<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');

echo '<pre>';
print_r($_SERVER['REMOTE_USER']);

直接调用它会打印出我的域\用户名

对于 Angular,我遵循本指南 -> https://blog.angular-university.io/angular-http/

角度:

this.courses$ = this.http
      .get<Course[]>("https://my_server/test.php",{ withCredentials: true })
      .pipe(
        map(data => _.values(data)),
        tap(console.log)
      )

这会产生一个 CORS 错误,在 DevTools 中可见。

"withCredentials: false" 似乎可以工作,但由于缺少凭据,我得到了“401 Unauthorized”。

如何修复 Angular 部分以向“my_server”发出请求,该请求与来自 IIS 的 Windows 身份验证一起使用?

【问题讨论】:

  • 不是我,但我们需要查看CORS错误的具体细节。应该有更详细的错误信息。
  • 您是否在 IIS 上安装了 CORS 模块?
  • 感谢有关 cors 错误的提示,因为没有比上图中看到的文本更多的文本,我在控制台中使用了一些 js 通过 xhr 调用触发了 cors 错误,这导致我返回解决方案

标签: php angular iis cors


【解决方案1】:

经过一番挖掘并感谢有帮助的 cmets,我找到了解决方案。

上图中没有更多文字,所以我使用控制台生成了一个新呼叫

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://my_server/test.php', true);
xhr.withCredentials = true;
xhr.send(null);

这导致了以下错误信息

Access to XMLHttpRequest at 'https://my_server/test.php' from origin 'http://localhost:4200' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

这反过来又导致了以下页面: https://sharepoint.stackexchange.com/questions/246313/how-to-add-multiple-url-to-access-control-allow-origin-header-in-sharepoint-2013

在删除原始的Access-Control-Allow-Origin 并在 web.config 中进行相同的编辑后,它现在看起来像这样

    <rewrite>
        <outboundRules>
            <clear />
            <rule name="AddCrossDomainHeader">
                <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
                    <add input="{HTTP_ORIGIN}" pattern="(http(s)?://((.+\.)?my_server|(.+\.)?localhost:4200" />
                </conditions>
                <action type="Rewrite" value="{C:0}" />
            </rule>
        </outboundRules>
    </rewrite>

这里重要的部分是(.+\.)?localhost:4200

【讨论】:

    猜你喜欢
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2019-02-25
    • 1970-01-01
    • 2022-10-07
    • 2021-10-09
    相关资源
    最近更新 更多