从源'http://localhost:4200' 'http://localhost:56557/api/tw/'访问 XMLHttpRequest 已被 CORS 策略阻止:



我会得到以下错误。当我尝试从Angular 5.0发送请求时。

请求标题字段访问访问控制 - 允许在前响应中的访问控制 - 允许头部不允许使用。

(使用Postman,API调用作品(

以下是角代码

let config = {
      headers: {
         "Content-Type": "application/json,charset=utf-8",
         "access-control-allow-origin": "*",
         "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
         "access-control-allow-headers": "Origin, X-Requested-With, Content-Type, Accept, Authorization"
        }
      }
    let obs = this.httpClient.post('http://localhost:56557/api/tw/',bodypara,config);

以下是Web配置更改

<system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <!--<remove name="OPTIONSVerbHandler" />-->
      <remove name="TRACEVerbHandler" />
      <!--<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />-->
      <add name="Browser Link for HTML" path="*.html" verb="*"
         type="System.Web.StaticFileHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
         resourceType="File" preCondition="integratedMode" />
    </handlers>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
  <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />
          <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
        </customHeaders>
      </httpProtocol>


  </system.webServer>

您已经告诉您的应用程序,access-control-allow-*标头不允许不包含在Access-Control-Allow-Headers选项中:

<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />

这就是为什么您会看到错误。

另外,access-control-allow-*标头都是响应标头,无论如何,服务器通常都会被服务器忽略。只需从您的请求中删除它们。

只需在服务器上的文件顶部添加以下代码。

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");

如果您在Angular或请求文件中设置特定标题

您需要如下所示输入它们:

Access-Control-Allow-Origin: [SCHEME]://[HOST]:[PORT_OPTIONAL]

方案 => http/https

主机 => server ip/domain name

port_optional => port //optional

相关内容

最新更新