代码之家  ›  专栏  ›  技术社区  ›  Ammar Ameerdeen

没有“Access Control Allow Origin”标头错误,即使它已在信号服务器上配置

  •  0
  • Ammar Ameerdeen  · 技术社区  · 7 年前

    我正在尝试连接到本地计算机上的信号器应用程序,该应用程序运行在与Angular 5应用程序不同的端口上。我遇到以下错误。我做错了什么。?

    加载失败 http://localhost:52527/chatHub :对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“access control Allow Origin”标头。“来源” http://localhost:4200 因此不允许访问。

    以下是角度代码。

    import { Component, OnInit } from '@angular/core';
    import { HubConnection } from '@aspnet/signalr-client';
    
    @Component({
      selector: 'app-register',
      templateUrl: './register.component.html',
      styleUrls: ['./register.component.css']
    })
    export class RegisterComponent implements OnInit {
      private hubConnection: HubConnection;
    
      constructor(private http: Http) {
      }
    
        ngOnInit() {
    
              this.hubConnection = new HubConnection('http://localhost:52527/chatHub');
    
              console.log(this.hubConnection);
              this.hubConnection
                .start()
                .then(function (){ 
                   console.log('Connection started!');
                })
                .catch(function(err) {
                  console.log(err);
                } );
              }
    
    }
    

    以下是服务器代码。

    [assembly: OwinStartup(typeof(SignalRChat.Startup))]
    namespace SignalRChat
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                // Any connection or hub wire up and configuration should go here
    
                app.Map("/signalr", map =>
                {
                    map.UseCors(CorsOptions.AllowAll);
                    var hubConfiguration = new HubConfiguration {};
                    map.RunSignalR(hubConfiguration);
                });
            }
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Ammar Ameerdeen    7 年前

    将以下行添加到Web。配置并修复了问题。

    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
                <add name="Access-Control-Allow-Headers" value="*" />
            <add name="Access-Control-Allow-Methods" value="*" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>