没有'Access-Control-Allow-Origin'标头错误,即使它已在SignalR服务器上配置

问题描述 投票:0回答:1

我正在尝试连接到本地计算机上的SignalR应用程序,在与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);
            });
        }
    }
}
signalr angular5
1个回答
0
投票

在Web.Config中添加了以下行,它修复了问题。

<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>
© www.soinside.com 2019 - 2024. All rights reserved.