【问题标题】:No 'Access-Control-Allow-Origin' header error, even though it has been configured on SignalR server没有“Access-Control-Allow-Origin”标头错误,即使它已在 SignalR 服务器上配置
【发布时间】:2018-01-01 17:12:16
【问题描述】:

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

无法加载 http://localhost:52527/chatHub:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 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】:

    在 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 2014-05-05
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 2016-01-21
      相关资源
      最近更新 更多